@tangle-network/agent-eval 0.207.4 → 0.209.1
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 +25 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-CEhxR_I3.d.ts → agent-profile-BGyt2z8U.d.ts} +3 -3
- package/dist/{agent-profile-CEhxR_I3.d.ts.map → agent-profile-BGyt2z8U.d.ts.map} +1 -1
- package/dist/{agent-profile-cell-BHcB-mZX.d.ts → agent-profile-cell-BNp-Js9F.d.ts} +2 -3
- package/dist/agent-profile-cell-BNp-Js9F.d.ts.map +1 -0
- package/dist/{agent-profile-cell-DcFW4vOc.js → agent-profile-cell-BYc0bxsL.js} +2 -2
- package/dist/agent-profile-cell-BYc0bxsL.js.map +1 -0
- package/dist/analyst/index.d.ts +12 -12
- package/dist/analyst/index.js +5 -5
- package/dist/{analyze-runs-GZ0VSwui.js → analyze-runs-0cdYMgob.js} +5 -5
- package/dist/{analyze-runs-GZ0VSwui.js.map → analyze-runs-0cdYMgob.js.map} +1 -1
- package/dist/{analyze-runs-CTJyUplR.d.ts → analyze-runs-BlslTkOJ.d.ts} +4 -4
- package/dist/{analyze-runs-CTJyUplR.d.ts.map → analyze-runs-BlslTkOJ.d.ts.map} +1 -1
- package/dist/{benchmark-command-DiFof9bz.js → benchmark-command-Cve7mHNC.js} +8 -8
- package/dist/{benchmark-command-DiFof9bz.js.map → benchmark-command-Cve7mHNC.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +5 -7
- package/dist/benchmarks/index.d.ts.map +1 -1
- package/dist/benchmarks/index.js +4 -4
- package/dist/builder-eval/index.js +1 -1
- package/dist/campaign/index.d.ts +7 -7
- package/dist/campaign/index.js +10 -10
- package/dist/{campaign-B8MqboM0.js → campaign-CvhmiLKa.js} +15 -15
- package/dist/{campaign-B8MqboM0.js.map → campaign-CvhmiLKa.js.map} +1 -1
- package/dist/{campaign-evidence-DW3Krxov.js → campaign-evidence-B5qsCHEn.js} +3 -3
- package/dist/{campaign-evidence-DW3Krxov.js.map → campaign-evidence-B5qsCHEn.js.map} +1 -1
- package/dist/cli.js +7 -7
- package/dist/contract/index.d.ts +9 -9
- package/dist/contract/index.js +8 -8
- package/dist/{default-registry-DZFWY2_E.d.ts → default-registry-Crk3QEy1.d.ts} +6 -6
- package/dist/{default-registry-DZFWY2_E.d.ts.map → default-registry-Crk3QEy1.d.ts.map} +1 -1
- package/dist/{default-registry-DX5R7_n9.js → default-registry-DF4Yp7HQ.js} +2 -2
- package/dist/{default-registry-DX5R7_n9.js.map → default-registry-DF4Yp7HQ.js.map} +1 -1
- package/dist/{define-agent-eval-BpRdb_Oa.js → define-agent-eval-Csd47ur_.js} +8 -8
- package/dist/{define-agent-eval-BpRdb_Oa.js.map → define-agent-eval-Csd47ur_.js.map} +1 -1
- package/dist/{define-agent-eval-Bmc4AYiB.d.ts → define-agent-eval-_nyV5nev.d.ts} +7 -7
- package/dist/{define-agent-eval-Bmc4AYiB.d.ts.map → define-agent-eval-_nyV5nev.d.ts.map} +1 -1
- package/dist/diagnosis/index.d.ts +2 -5
- package/dist/diagnosis/index.d.ts.map +1 -1
- package/dist/diagnosis/index.js +2 -26
- package/dist/diagnosis/index.js.map +1 -1
- package/dist/{dspy-rlm-engine-AJqjFUUr.js → dspy-rlm-engine-BpaKVKJA.js} +3 -3
- package/dist/{dspy-rlm-engine-AJqjFUUr.js.map → dspy-rlm-engine-BpaKVKJA.js.map} +1 -1
- package/dist/{engine-DProXJ7A.d.ts → engine-D-YZ32ZJ.d.ts} +5 -12
- package/dist/engine-D-YZ32ZJ.d.ts.map +1 -0
- package/dist/{eval-campaign-DU_p8qVt.js → eval-campaign-C31Qbv77.js} +4 -4
- package/dist/{eval-campaign-DU_p8qVt.js.map → eval-campaign-C31Qbv77.js.map} +1 -1
- package/dist/evaluation.d.ts +2 -2
- package/dist/{exact-types-Cq6xXNVR.d.ts → exact-types-DjhfZglz.d.ts} +2 -2
- package/dist/{exact-types-Cq6xXNVR.d.ts.map → exact-types-DjhfZglz.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +2 -2
- package/dist/experiment/index.js +5 -5
- package/dist/{external-optimizer-process-Bemjoy8y.js → external-optimizer-process-D2Txd-7D.js} +2 -2
- package/dist/{external-optimizer-process-Bemjoy8y.js.map → external-optimizer-process-D2Txd-7D.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-d_EQrcTS.js → external-optimizer-subprocess-C0EsxEbI.js} +11 -3
- package/dist/{external-optimizer-subprocess-d_EQrcTS.js.map → external-optimizer-subprocess-C0EsxEbI.js.map} +1 -1
- package/dist/{feedback-trajectory-C6Z8PRoF.d.ts → feedback-trajectory-CX01700m.d.ts} +3 -3
- package/dist/{feedback-trajectory-C6Z8PRoF.d.ts.map → feedback-trajectory-CX01700m.d.ts.map} +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/{index-LAFht3x_.d.ts → index-BHh9Z9El.d.ts} +9 -9
- package/dist/{index-LAFht3x_.d.ts.map → index-BHh9Z9El.d.ts.map} +1 -1
- package/dist/{index-B9mXrS0W.d.ts → index-Ddi5M-TQ.d.ts} +8 -8
- package/dist/{index-B9mXrS0W.d.ts.map → index-Ddi5M-TQ.d.ts.map} +1 -1
- package/dist/{index-CbBfavbT.d.ts → index-H-u7f-w3.d.ts} +2 -2
- package/dist/{index-CbBfavbT.d.ts.map → index-H-u7f-w3.d.ts.map} +1 -1
- package/dist/{index-DkucR0KJ.d.ts → index-UxNTvn-w.d.ts} +6 -6
- package/dist/{index-DkucR0KJ.d.ts.map → index-UxNTvn-w.d.ts.map} +1 -1
- package/dist/index.d.ts +27 -36
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +25 -87
- package/dist/index.js.map +1 -1
- package/dist/{kind-factory-Cn1lbsAd.js → kind-factory-ivTx6koH.js} +2 -11
- package/dist/{kind-factory-Cn1lbsAd.js.map → kind-factory-ivTx6koH.js.map} +1 -1
- package/dist/{llm-judge-DBrxRG2D.js → llm-judge-C0256VT_.js} +8 -8
- package/dist/{llm-judge-DBrxRG2D.js.map → llm-judge-C0256VT_.js.map} +1 -1
- package/dist/{matrix-Cqkk7eYI.d.ts → matrix-jHTsHEkR.d.ts} +2 -2
- package/dist/{matrix-Cqkk7eYI.d.ts.map → matrix-jHTsHEkR.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +1 -1
- package/dist/meta-eval/index.js +1 -1
- package/dist/{mint-C1W8w5wo.d.ts → mint-CDy-brUR.d.ts} +2 -2
- package/dist/{mint-C1W8w5wo.d.ts.map → mint-CDy-brUR.d.ts.map} +1 -1
- package/dist/{mint-CWG-s2mI.js → mint-Csor1BLJ.js} +2 -2
- package/dist/{mint-CWG-s2mI.js.map → mint-Csor1BLJ.js.map} +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{paired-arms-CgWT7sHy.js → paired-arms-B5v-X7No.js} +2 -4
- package/dist/{paired-arms-CgWT7sHy.js.map → paired-arms-B5v-X7No.js.map} +1 -1
- package/dist/pipelines/index.d.ts +1 -1
- package/dist/pipelines/index.js +2 -2
- package/dist/{prime-protocol-Csr9kcOM.d.ts → prime-protocol-B7et3tI7.d.ts} +2 -2
- package/dist/{prime-protocol-Csr9kcOM.d.ts.map → prime-protocol-B7et3tI7.d.ts.map} +1 -1
- package/dist/{produced-state-DyTuvglz.js → produced-state-CgB9g0VX.js} +3 -3
- package/dist/{produced-state-DyTuvglz.js.map → produced-state-CgB9g0VX.js.map} +1 -1
- package/dist/profile-cell.d.ts +2 -2
- package/dist/profile-cell.js +2 -2
- package/dist/{query-DlV0pdx4.js → query-B1D1qp2Z.js} +2 -2
- package/dist/{query-DlV0pdx4.js.map → query-B1D1qp2Z.js.map} +1 -1
- package/dist/{query-DBUQhehH.d.ts → query-DK1nWcmp.d.ts} +2 -3
- package/dist/{query-DBUQhehH.d.ts.map → query-DK1nWcmp.d.ts.map} +1 -1
- package/dist/{registry-DMkmhBQ5.d.ts → registry-BL7H33tj.d.ts} +3 -3
- package/dist/{registry-DMkmhBQ5.d.ts.map → registry-BL7H33tj.d.ts.map} +1 -1
- package/dist/{release-confidence-CkoXFx9I.d.ts → release-confidence-C4kI7lQi.d.ts} +4 -12
- package/dist/release-confidence-C4kI7lQi.d.ts.map +1 -0
- package/dist/{release-confidence-CiFg1EPq.js → release-confidence-Dbe9AS_X.js} +2 -2
- package/dist/{release-confidence-CiFg1EPq.js.map → release-confidence-Dbe9AS_X.js.map} +1 -1
- package/dist/{report-command-pXtxg5YK.js → report-command-CtIIsQKP.js} +3 -28
- package/dist/{report-command-pXtxg5YK.js.map → report-command-CtIIsQKP.js.map} +1 -1
- package/dist/reporting.d.ts +3 -3
- package/dist/reporting.js +3 -3
- package/dist/{researcher-CZFZjj-u.d.ts → researcher-DuIJ9IaA.d.ts} +4 -4
- package/dist/{researcher-CZFZjj-u.d.ts.map → researcher-DuIJ9IaA.d.ts.map} +1 -1
- package/dist/{reward-hacking-Cyk-QHk9.d.ts → reward-hacking-C6Kp54Av.d.ts} +2 -2
- package/dist/{reward-hacking-Cyk-QHk9.d.ts.map → reward-hacking-C6Kp54Av.d.ts.map} +1 -1
- package/dist/reward-nw2xZGZG.js.map +1 -1
- package/dist/rl.d.ts +10 -29
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +6 -6
- package/dist/rl.js.map +1 -1
- package/dist/rollout/index.d.ts +2 -2
- package/dist/rollout/index.js +2 -2
- package/dist/{rollout-l9w3Gdvh.js → rollout-BZqQc0YY.js} +2 -2
- package/dist/{rollout-l9w3Gdvh.js.map → rollout-BZqQc0YY.js.map} +1 -1
- package/dist/{rubric-predictive-validity-DIUwJJ9Y.d.ts → rubric-predictive-validity-BiNNEjpG.d.ts} +2 -2
- package/dist/{rubric-predictive-validity-DIUwJJ9Y.d.ts.map → rubric-predictive-validity-BiNNEjpG.d.ts.map} +1 -1
- package/dist/{run-record-BRlM99rX.js → run-record-DlTZ_lqe.js} +3 -13
- package/dist/run-record-DlTZ_lqe.js.map +1 -0
- package/dist/{run-record-BB290Y9A.js → run-record-ES07wfz9.js} +2 -2
- package/dist/{run-record-BB290Y9A.js.map → run-record-ES07wfz9.js.map} +1 -1
- package/dist/{run-record-DF-fuu31.d.ts → run-record-p2AYTrCn.d.ts} +3 -7
- package/dist/run-record-p2AYTrCn.d.ts.map +1 -0
- package/dist/search/index.d.ts +2 -24
- package/dist/search/index.d.ts.map +1 -1
- package/dist/search/index.js +3 -3
- package/dist/{search-kernel-mzeNuzr8.js → search-kernel-Bfe3kzRk.js} +45 -3
- package/dist/search-kernel-Bfe3kzRk.js.map +1 -0
- package/dist/{search-kernel-CzTWtv5d.d.ts → search-kernel-ah2GESe3.d.ts} +19 -4
- package/dist/search-kernel-ah2GESe3.d.ts.map +1 -0
- package/dist/{search-ledger-CXQPwdWz.js → search-ledger-aMTNQn_m.js} +2 -2
- package/dist/{search-ledger-CXQPwdWz.js.map → search-ledger-aMTNQn_m.js.map} +1 -1
- package/dist/{search-shipper-DhhofkDX.js → search-shipper-DKXWuLnp.js} +2 -2
- package/dist/{search-shipper-DhhofkDX.js.map → search-shipper-DKXWuLnp.js.map} +1 -1
- package/dist/{search-summary-CDURlgZR.js → search-summary-DK1bwTAf.js} +2 -2
- package/dist/{search-summary-CDURlgZR.js.map → search-summary-DK1bwTAf.js.map} +1 -1
- package/dist/{semantic-concept-judge-DDxUiWIz.js → semantic-concept-judge-BQxZyXdN.js} +3 -3
- package/dist/{semantic-concept-judge-DDxUiWIz.js.map → semantic-concept-judge-BQxZyXdN.js.map} +1 -1
- package/dist/{sequential-DMqr3sni.js → sequential-BOzBND4t.js} +2 -2
- package/dist/{sequential-DMqr3sni.js.map → sequential-BOzBND4t.js.map} +1 -1
- package/dist/{skillopt-optimization-method-D0-bMRGu.js → skillopt-optimization-method-BCojvoP1.js} +6 -6
- package/dist/{skillopt-optimization-method-D0-bMRGu.js.map → skillopt-optimization-method-BCojvoP1.js.map} +1 -1
- package/dist/{statistical-heldout-DFKtp-Qm.d.ts → statistical-heldout-D0rX_IDl.d.ts} +4 -5
- package/dist/statistical-heldout-D0rX_IDl.d.ts.map +1 -0
- package/dist/{store-otlp-BA7G1Du-.js → store-otlp-__ebQ6Hn.js} +2 -2
- package/dist/{store-otlp-BA7G1Du-.js.map → store-otlp-__ebQ6Hn.js.map} +1 -1
- package/dist/{store-tool-spans-DKoVbE-w.js → store-tool-spans-TbRBuIM7.js} +3 -3
- package/dist/{store-tool-spans-DKoVbE-w.js.map → store-tool-spans-TbRBuIM7.js.map} +1 -1
- package/dist/{store-tool-spans-9YJNMP-z.d.ts → store-tool-spans-wQ9idsnn.d.ts} +5 -5
- package/dist/{store-tool-spans-9YJNMP-z.d.ts.map → store-tool-spans-wQ9idsnn.d.ts.map} +1 -1
- package/dist/{summary-report-fXurE2TR.js → summary-report-BsaEFEwA.js} +3 -3
- package/dist/{summary-report-fXurE2TR.js.map → summary-report-BsaEFEwA.js.map} +1 -1
- package/dist/{summary-report-DvvesgR_.d.ts → summary-report-CK0ueoJd.d.ts} +2 -2
- package/dist/{summary-report-DvvesgR_.d.ts.map → summary-report-CK0ueoJd.d.ts.map} +1 -1
- package/dist/supervisor-run/index.d.ts +0 -8
- package/dist/supervisor-run/index.d.ts.map +1 -1
- package/dist/supervisor-run/index.js +2 -2
- package/dist/{systemone-review-Bt4JcxMc.d.ts → systemone-review-BReh3mvm.d.ts} +2 -2
- package/dist/{systemone-review-Bt4JcxMc.d.ts.map → systemone-review-BReh3mvm.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/{tool-groups-j19pmOfP.d.ts → tool-groups-v28A-ZAF.d.ts} +3 -3
- package/dist/tool-groups-v28A-ZAF.d.ts.map +1 -0
- package/dist/{tool-waste-x_E8h9Ih.js → tool-waste-BYt5rdt8.js} +2 -2
- package/dist/{tool-waste-x_E8h9Ih.js.map → tool-waste-BYt5rdt8.js.map} +1 -1
- package/dist/{tool-waste-DxlebQkx.d.ts → tool-waste-Wi4g6Ekb.d.ts} +2 -2
- package/dist/{tool-waste-DxlebQkx.d.ts.map → tool-waste-Wi4g6Ekb.d.ts.map} +1 -1
- package/dist/{trace-questions-dRvmsbTk.d.ts → trace-questions-C26UvI3D.d.ts} +3 -3
- package/dist/{trace-questions-dRvmsbTk.d.ts.map → trace-questions-C26UvI3D.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +2 -9
- package/dist/trace-repair/index.d.ts.map +1 -1
- package/dist/trace-repair/index.js +1 -1
- package/dist/traces.d.ts +6 -8
- package/dist/traces.d.ts.map +1 -1
- package/dist/traces.js +6 -6
- package/dist/trajectory-replay/index.d.ts +0 -2
- package/dist/trajectory-replay/index.d.ts.map +1 -1
- package/dist/trajectory-replay/index.js +1 -1
- package/dist/{tree-CN8mlzUO.js → tree-CZ78tiPg.js} +4 -24
- package/dist/tree-CZ78tiPg.js.map +1 -0
- package/dist/{types-CFCUZk0B.d.ts → types-Dv9sYwBB.d.ts} +4 -4
- package/dist/{types-CFCUZk0B.d.ts.map → types-Dv9sYwBB.d.ts.map} +1 -1
- package/dist/{types-DAPpAkd4.d.ts → types-KEkKkETv.d.ts} +2 -2
- package/dist/{types-DAPpAkd4.d.ts.map → types-KEkKkETv.d.ts.map} +1 -1
- package/dist/{types-BlSBUNRd.d.ts → types-tWFY6bON.d.ts} +3 -3
- package/dist/{types-BlSBUNRd.d.ts.map → types-tWFY6bON.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +1 -1
- package/docs/public-api.md +399 -424
- package/docs/quickstart-external.md +268 -0
- package/docs/search-ledger.md +4 -1
- package/package.json +3 -3
- package/dist/agent-profile-cell-BHcB-mZX.d.ts.map +0 -1
- package/dist/agent-profile-cell-DcFW4vOc.js.map +0 -1
- package/dist/engine-DProXJ7A.d.ts.map +0 -1
- package/dist/release-confidence-CkoXFx9I.d.ts.map +0 -1
- package/dist/run-record-BRlM99rX.js.map +0 -1
- package/dist/run-record-DF-fuu31.d.ts.map +0 -1
- package/dist/search-kernel-CzTWtv5d.d.ts.map +0 -1
- package/dist/search-kernel-mzeNuzr8.js.map +0 -1
- package/dist/statistical-heldout-DFKtp-Qm.d.ts.map +0 -1
- package/dist/tool-groups-j19pmOfP.d.ts.map +0 -1
- package/dist/tree-CN8mlzUO.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tree-CN8mlzUO.js","names":["signed","plural","orient","result","plural","plural"],"sources":["../src/search/lenses/edit-credit.ts","../src/search/lenses/front.ts","../src/search/lenses/geometry.ts","../src/math/cholesky.ts","../src/math/symmetric-eigen.ts","../src/search/lenses/plateau.ts","../src/search/lenses/landscape.ts","../src/search/lenses/meta-search.ts","../src/search/lenses/skill-manifold.ts","../src/search/lenses/task-matrix.ts","../src/search/lenses/tree.ts"],"sourcesContent":["/**\n * `editCredit`: the edits of a search as genes, followed down its lineage.\n *\n * Every lineage edge is a parent-to-child change of an artifact. The lens\n * diffs the two artifacts line by line (whitespace-normalized) and cuts each\n * changed run into paragraphs: an added paragraph is an `insert` gene, a\n * removed paragraph a `delete` gene. A gene's id hashes its kind, its location\n * in the artifact and its normalized lines, so the same edit has the same id\n * wherever and whenever a proposer makes it. A node carries an insert gene\n * when the paragraph is present at that location, and a delete gene when it is\n * absent. Carrying is read from each node's content, so it follows merges,\n * re-proposals and reverts without any bookkeeping in the record.\n *\n * A step is one lineage parent and its child. A gene flips on a step when the\n * parent and the child disagree on carrying it. The gene's credit pairs, per\n * step, the side that carries it against the side that lacks it on the units\n * both scored, and averages those contrasts across its steps inside each unit.\n * Only clean steps count: steps on which nothing flips except edits introduced\n * together with the gene. A merge that also brings in the other parent's edits\n * is therefore not evidence for any one of them, and genes that always move\n * together are reported as linked, because their credits are one number.\n *\n * Interactions compare a gene's step contrasts where another gene is present\n * against where it is absent, in both directions, and are flagged after a Holm\n * correction for a factorial test rather than claimed.\n *\n * The lens reads node artifacts through `readArtifact`, which the caller backs\n * with verified blob bytes. An artifact the caller cannot read, and a code\n * surface whose patch bytes are not in the ledger, leave the node's content\n * unknown: its steps yield no genes and no contrasts.\n */\n\nimport { type AgentProfileResourceRef, defineInlineResource } from '@tangle-network/agent-interface'\nimport { searchEstimateMethod, seedFromDigest } from '../../campaign/estimate-node'\nimport type {\n NodeEstimate,\n SearchArtifactRef,\n SearchEdgeOperator,\n SearchEdgeRecordedEvent,\n SearchEstimateMethod,\n SearchSourceRef,\n SearchSplit,\n} from '../../campaign/search-ledger-types'\nimport type { SearchNode, SearchStateView } from '../../campaign/search-state'\nimport { canonicalString, compareCodeUnits, hashCanonical } from '../../ledger-core/canonical'\nimport { minimumPairsForPairedDeltaTest, pairedDeltaTest } from '../../paired-delta-test'\nimport {\n BOOTSTRAP_GATE_MIN_N,\n DECISION_PAIRED_DELTA_STATISTIC,\n holm,\n pairedSignTest,\n} from '../../statistics'\nimport { type LensResult, type LensSignal, rankingSplit } from './shared'\n\nconst CONFIDENCE = 0.95\nconst RESAMPLES = 2000\nconst DESCRIPTIVE_FROM = minimumPairsForPairedDeltaTest(CONFIDENCE)\nconst INTERACTION_ALPHA = 0.05\nconst DEFAULT_INTERACTION_GENES = 24\n/** Signal name a policy reads. */\nexport const EDIT_CREDIT_SIGNAL = 'reusableHunks'\n\n/**\n * Every choice a credit depends on. Its digest is the estimator revision each\n * credit names, so two readers that report the same revision and the same\n * `cellSetDigest` report the same numbers.\n */\nconst CREDIT_DEFINITION = {\n name: 'tangle.edit-credit.2026-09',\n gene: 'a paragraph of whitespace-normalized lines added (insert) or removed (delete) at one artifact location',\n step: 'one lineage parent and its child, both with known content and neither invalid',\n clean:\n 'the gene flips on the step and every gene that flips was introduced on one edge that introduced it',\n unit: 'mean of a node’s scored cells in the unit; per unit, carrier-side and lacking-side means averaged over the clean steps where both sides scored it',\n statistic: DECISION_PAIRED_DELTA_STATISTIC,\n interval: 'percentile paired bootstrap',\n confidence: CONFIDENCE,\n resamples: RESAMPLES,\n rng: 'mulberry32',\n seed: 'the first 32 bits of cellSetDigest',\n signTest: 'exact, one-sided toward improvement in the objective direction',\n methods: {\n none: 'below 2 units',\n insufficient: `below ${DESCRIPTIVE_FROM} units`,\n descriptive: `below ${BOOTSTRAP_GATE_MIN_N} units`,\n bootstrap: `from ${BOOTSTRAP_GATE_MIN_N} units`,\n },\n} as const\n\n/** The estimator every gene credit names. */\nexport const EDIT_CREDIT_ESTIMATOR: SearchSourceRef = {\n uri: 'npm:@tangle-network/agent-eval/search#editCredit',\n revision: hashCanonical(CREDIT_DEFINITION),\n}\n\nexport interface EditCreditOptions {\n /**\n * The parsed content a node's artifact reference names, or undefined when\n * it is unavailable. The caller must verify the bytes against `ref.sha256`;\n * the lens trusts what it is handed.\n */\n readArtifact(ref: SearchArtifactRef): unknown | undefined\n /** Split credit is measured on. Default: selection when the search declares\n * one, else train. */\n split?: SearchSplit\n /** Genes tested for pairwise interaction: those with the most measured\n * units, one per linkage group. Default 24, so at most 276 pairs. */\n interactionGenes?: number\n}\n\nexport type EditGeneVerdict = 'reusable' | 'harmful' | 'unresolved' | 'insufficient'\n\nexport interface EditIntroduction {\n nodeId: string\n edgeId: string\n operator: SearchEdgeOperator\n parents: string[]\n /** The edge is a re-proposal into a node registered earlier. */\n reproposal: boolean\n}\n\nexport interface EditGene {\n geneId: string\n kind: 'insert' | 'delete'\n /** Where in the artifact: `prompt`, `component:<name>`, or a JSON path such\n * as `/prompt/systemPrompt`. */\n path: string\n /** Normalized lines: the gene's identity. */\n lines: string[]\n /** The lines as the first proposer wrote them. */\n text: string\n /** Lineage edges whose child carries the gene while none of its parents\n * did, in ledger order. More than one means a proposer made the same edit\n * again. */\n introduced: EditIntroduction[]\n /** Lineage edges whose child lost the gene that a parent carried. */\n dropped: number\n /** Genes introduced on the edge that first introduced this one: the edit\n * it was born in, itself included, in artifact order. */\n edit: string[]\n /** Nodes with known content that carry it and are not invalid. */\n carriers: number\n /** `invalid` carriers (judge integrity or admission failures), excluded from\n * every contrast; an edit that makes nodes invalid shows here. */\n invalidCarriers: number\n steps: {\n /** Steps on which the gene flips. */\n flips: number\n /** Of those, the steps its credit reads. */\n clean: number\n /** Clean steps on which the child gained the gene. */\n gained: number\n /** Clean steps on which the child lost it. */\n lost: number\n }\n /** Carrying side against lacking side on clean steps; `delta` is carrier\n * minus non-carrier in the metric's units. */\n credit: NodeEstimate\n verdict: EditGeneVerdict\n /** The first gene of this gene's linkage group: genes with the same clean\n * steps, oriented the same way, have one credit and cannot be separated.\n * Null when the gene has no partner. */\n linkage: string | null\n}\n\nexport interface EditInteraction {\n genes: [string, string]\n /** Clean steps of each gene, split by whether both ends carry the other. */\n steps: {\n firstWithSecond: number\n firstWithoutSecond: number\n secondWithFirst: number\n secondWithoutFirst: number\n }\n /** Units with a contrast in at least one direction. */\n units: number\n method: SearchEstimateMethod\n /** Mean per-unit difference of a gene's credit with the other present minus\n * with it absent, both directions averaged, in the metric's units; null\n * below 2 units. */\n interaction: number | null\n /** Percentile bootstrap spread from 6 units; null below 6 or when every\n * per-unit contrast is equal. */\n interval: [number, number] | null\n indeterminate: boolean\n /** Exact two-sided sign test; null below 6 units. */\n signP: number | null\n /** Holm-adjusted over every pair tested; null when this pair was not tested. */\n adjustedP: number | null\n interacting: boolean\n /** The pair does better together than their separate credits add up to, in\n * the objective's direction. Null without an interaction estimate. */\n synergy: boolean | null\n}\n\nexport interface EditSkillCandidate {\n /** An inline skill resource: add it to `profile.resources.skills` (with\n * `resources.failOnError: true`) and pass `improveOptions` to agent-runtime\n * `improve()` with `method: officialSkillOpt(...)` to optimize it. */\n resource: Extract<AgentProfileResourceRef, { kind: 'inline' }>\n improveOptions: { surface: 'skills'; skills: { resourceName: string } }\n /** The linked insert genes the skill holds, in artifact order. */\n genes: string[]\n path: string\n credit: NodeEstimate\n}\n\nexport interface EditLineageRow {\n nodeId: string\n ordinal: number\n depth: number | null\n primaryParentId: string | null\n parents: string[]\n operator: SearchEdgeOperator | null\n status: SearchNode['status']\n /** Every gene this node carries. */\n carries: string[]\n contentKnown: boolean\n}\n\nexport interface EditCreditData {\n split: SearchSplit\n direction: 'maximize' | 'minimize'\n edges: {\n /** Edges with at least one parent registered before the child in this search. */\n lineage: number\n /** Of those, edges whose child and every lineage parent had known content. */\n read: number\n /** Why an edge's content was unknown, with counts. */\n unknown: Record<string, number>\n }\n /** Distinct parent-child pairs with known content; those with an invalid\n * end are excluded from every contrast. */\n steps: { total: number; invalidEnd: number }\n nodes: { total: number; contentUnknown: number; invalid: number }\n /** Reusable, harmful, unresolved, then insufficient; within each, by credit. */\n genes: EditGene[]\n counts: Record<EditGeneVerdict, number>\n /** Independent edits per verdict: linkage groups, and for genes without a\n * clean step the edit they were born in. */\n editCounts: Record<EditGeneVerdict, number>\n interactions: {\n genesConsidered: number\n /** Pairs with a with-and-without split in at least one direction. */\n pairsWithContexts: number\n /** Pairs with 6 or more units and a non-degenerate contrast. */\n pairsTested: number\n alpha: number\n correction: 'holm'\n /** Flagged pairs first, then by adjusted p. */\n pairs: EditInteraction[]\n }\n skillCandidates: EditSkillCandidate[]\n /** What the reusable count would be with no true effect anywhere: credit is\n * not adjusted for the number of edits, so read `reusable` against this. */\n chance: {\n /** Independent edits measured on 6 or more units. */\n measuredEdits: number\n /** Sum over measured edits of the chance the verdict calls one reusable\n * when it has no effect. */\n expectedReusable: number\n method: string\n }\n /** Rows in lineage order (depth-first along primary parents): the matrix a\n * genealogy view draws, genes as columns. */\n lineage: EditLineageRow[]\n method: {\n estimator: SearchSourceRef\n credit: string\n verdict: string\n interaction: string\n multiplicity: string\n /** The known bias of a lineage contrast in a search. */\n selectionBias: string\n }\n}\n\n/** The signal: independent edits `pairedDeltaTest` finds improve the\n * objective, null below 6 units on every gene. */\nexport interface EditCreditSignal extends LensSignal<number | null> {\n /** How the value was computed, or why it is null. */\n basis: string\n /** The first gene of each reusable edit, best first: the hunks a proposer\n * reuses or a skill extraction starts from. */\n top: string[]\n}\n\nexport type EditCreditResult = LensResult<EditCreditData, number | null> & {\n signal: EditCreditSignal\n}\n\ninterface PathText {\n raw: string[]\n norm: string[]\n}\n\ntype KnownContent = { known: true; paths: Map<string, PathText>; haystacks: Map<string, string> }\ntype NodeContent = KnownContent | { known: false; reason: string }\n\ninterface GeneCut {\n kind: 'insert' | 'delete'\n path: string\n lines: string[]\n needle: string\n text: string\n /** Position in the child's diff: artifact order. */\n position: number\n}\n\ninterface GeneRecord extends GeneCut {\n geneId: string\n locus: string\n introduced: EditIntroduction[]\n dropped: number\n /** Ledger order of the first introduction, then position in the artifact. */\n order: [number, number]\n}\n\ninterface Step {\n key: string\n parentId: string\n childId: string\n /** Genes whose carrying differs between parent and child. */\n flips: Set<string>\n}\n\n/**\n * The edit-credit lens. Pure: the result depends only on `state` and what\n * `readArtifact` returns for its references.\n */\nexport function editCredit(state: SearchStateView, options: EditCreditOptions): EditCreditResult {\n const header = state.header\n if (!header) throw new Error(`editCredit: search ${state.searchId} has not been opened`)\n const split = options.split ?? rankingSplit(state)\n const direction = header.objective.direction\n const sign = direction === 'maximize' ? 1 : -1\n const interactionGenes = options.interactionGenes ?? DEFAULT_INTERACTION_GENES\n if (!Number.isSafeInteger(interactionGenes) || interactionGenes < 0) {\n throw new Error(`editCredit: interactionGenes must be a non-negative integer`)\n }\n\n const nodes = state.nodes()\n const byId = new Map(nodes.map((node) => [node.nodeId, node]))\n const contents = new Map<string, NodeContent>()\n for (const node of nodes) contents.set(node.nodeId, nodeContent(options, node.artifact))\n const known = (nodeId: string) => contents.get(nodeId) as KnownContent\n const invalid = new Set(nodes.filter((node) => node.status === 'invalid').map((n) => n.nodeId))\n\n // Genes: every lineage edge, in ledger order. A gene is one locus (a\n // location and its lines); an edge that re-adds a paragraph a delete gene\n // removed drops that gene rather than creating a second one.\n const genes = new Map<string, GeneRecord>()\n const byLocus = new Map<string, GeneRecord>()\n const introducedOn = new Map<string, string[]>()\n const unknownEdges: Record<string, number> = {}\n const stepList: Step[] = []\n const stepKeys = new Set<string>()\n let lineageEdges = 0\n let readEdges = 0\n let edgeOrdinal = 0\n for (const edge of state.edges()) {\n edgeOrdinal += 1\n const child = byId.get(edge.childNodeId)!\n const parents = lineageParents(state, edge, child, byId)\n if (parents.length === 0) continue\n lineageEdges += 1\n const missing = [child.nodeId, ...parents]\n .map((nodeId) => contents.get(nodeId)!)\n .find((content) => !content.known)\n if (missing && !missing.known) {\n unknownEdges[missing.reason] = (unknownEdges[missing.reason] ?? 0) + 1\n continue\n }\n readEdges += 1\n const childContent = known(child.nodeId)\n const reproposal = child.edgeIds[0] !== edge.edgeId\n // A parent registered after the child (a re-proposal from a later node) or\n // in another search is not in the lineage, so whether it carried a gene is\n // not known here: the edge's steps still count, its introductions do not.\n const wholeLineage = edge.parents.every(\n (parent) => parent.searchId === state.searchId && parents.includes(parent.nodeId),\n )\n const cuts = new Map<string, GeneCut>()\n for (const parentId of parents) {\n const key = `${parentId}>${child.nodeId}`\n if (!stepKeys.has(key)) {\n stepKeys.add(key)\n stepList.push({ key, parentId, childId: child.nodeId, flips: new Set() })\n }\n for (const cut of edgeCuts(known(parentId), childContent)) {\n const locus = locusOf(cut)\n if (!cuts.has(locus)) cuts.set(locus, cut)\n }\n }\n if (!wholeLineage) continue\n const introducedHere: string[] = []\n for (const [locus, cut] of cuts) {\n const existing = byLocus.get(locus)\n const gene = existing ?? cut\n const childCarries = carries(childContent, gene)\n const parentCarries = parents.filter((parentId) => carries(known(parentId), gene))\n if (existing && !childCarries && parentCarries.length > 0) {\n existing.dropped += 1\n continue\n }\n // A merge child that took the edit from another parent inherited it; a\n // deletion of one copy of a repeated block leaves the child without it.\n if (!childCarries || parentCarries.length > 0) continue\n let record = existing\n if (!record) {\n const geneId = `gene_${hashCanonical({ kind: cut.kind, path: cut.path, lines: cut.lines })\n .slice('sha256:'.length)\n .slice(0, 24)}`\n record = {\n ...cut,\n geneId,\n locus,\n introduced: [],\n dropped: 0,\n order: [edgeOrdinal, cut.position],\n }\n genes.set(geneId, record)\n byLocus.set(locus, record)\n }\n record.introduced.push({\n nodeId: child.nodeId,\n edgeId: edge.edgeId,\n operator: edge.operator,\n parents,\n reproposal,\n })\n introducedHere.push(record.geneId)\n }\n introducedOn.set(edge.edgeId, introducedHere)\n }\n\n // Carrying: every gene against every node whose content is known.\n const carriersOf = new Map<string, Set<string>>()\n const carried = new Map<string, string[]>()\n for (const record of genes.values()) {\n const set = new Set<string>()\n for (const node of nodes) {\n const content = contents.get(node.nodeId)!\n if (content.known && carries(content, record)) {\n set.add(node.nodeId)\n appendTo(carried, node.nodeId, record.geneId)\n }\n }\n carriersOf.set(record.geneId, set)\n }\n for (const step of stepList) {\n for (const [geneId, set] of carriersOf) {\n if (set.has(step.parentId) !== set.has(step.childId)) step.flips.add(geneId)\n }\n }\n const measurable = stepList.filter(\n (step) => !invalid.has(step.parentId) && !invalid.has(step.childId),\n )\n\n // The edits each gene was introduced in: per introducing edge, the genes\n // that edge introduced. The first is the edit the gene was born in.\n const editsOf = new Map<string, Array<ReadonlySet<string>>>()\n for (const record of genes.values()) {\n editsOf.set(\n record.geneId,\n record.introduced.map((introduction) => new Set(introducedOn.get(introduction.edgeId)!)),\n )\n }\n\n const unitMeansOf = memo((nodeId: string) => {\n const means = new Map<string, number>()\n for (const unit of state.unitScores(nodeId, split)) means.set(unit.unitId, unit.mean)\n return means\n })\n const cellsDigestOf = memo((nodeId: string) =>\n state\n .scoredCells(nodeId, split)\n .map((cell) => [cell.cellId, cell.unitId, cell.attempt, cell.score] as const)\n .sort((left, right) => compareCodeUnits(left[0], right[0])),\n )\n\n interface Oriented {\n step: Step\n carrierId: string\n lackingId: string\n }\n const cleanOf = new Map<string, Oriented[]>()\n const flipCount = new Map<string, number>()\n for (const step of measurable) {\n for (const geneId of step.flips) {\n flipCount.set(geneId, (flipCount.get(geneId) ?? 0) + 1)\n // Clean: every change on the step belongs to one edit that introduced\n // the gene, so the contrast is that edit's, not a mixture.\n const inOneEdit = editsOf\n .get(geneId)!\n .some((edit) => [...step.flips].every((other) => edit.has(other)))\n if (!inOneEdit) continue\n const childCarries = carriersOf.get(geneId)!.has(step.childId)\n const oriented = {\n step,\n carrierId: childCarries ? step.childId : step.parentId,\n lackingId: childCarries ? step.parentId : step.childId,\n }\n appendTo(cleanOf, geneId, oriented)\n }\n }\n\n const credits = new Map<string, { credit: NodeEstimate; verdict: EditGeneVerdict }>()\n for (const record of genes.values()) {\n const steps = cleanOf.get(record.geneId) ?? []\n const perUnit = new Map<string, { carrier: number; lacking: number; count: number }>()\n for (const { carrierId, lackingId } of steps) {\n const lacking = unitMeansOf(lackingId)\n for (const [unitId, carrierMean] of unitMeansOf(carrierId)) {\n const lackingMean = lacking.get(unitId)\n if (lackingMean === undefined) continue\n const entry = perUnit.get(unitId) ?? { carrier: 0, lacking: 0, count: 0 }\n entry.carrier += carrierMean\n entry.lacking += lackingMean\n entry.count += 1\n perUnit.set(unitId, entry)\n }\n }\n const unitIds = [...perUnit.keys()].sort(compareCodeUnits)\n // The contrast is the oriented steps, not the gene: linked genes read the\n // same cells and so report the same numbers.\n const cellSetDigest = hashCanonical({\n split,\n steps: steps\n .map(({ carrierId, lackingId }) => [\n carrierId,\n lackingId,\n cellsDigestOf(carrierId),\n cellsDigestOf(lackingId),\n ])\n .sort((left, right) => compareCodeUnits(canonicalString(left), canonicalString(right))),\n })\n const carrierUnits = new Set<string>()\n for (const { carrierId } of steps)\n for (const unitId of unitMeansOf(carrierId).keys()) carrierUnits.add(unitId)\n credits.set(\n record.geneId,\n pairedEstimate({\n against: `${record.geneId}:lacking`,\n split,\n direction,\n units: carrierUnits.size,\n lacking: unitIds.map((unitId) => perUnit.get(unitId)!.lacking / perUnit.get(unitId)!.count),\n carrier: unitIds.map((unitId) => perUnit.get(unitId)!.carrier / perUnit.get(unitId)!.count),\n cellSetDigest,\n }),\n )\n }\n\n // Linkage: the same clean steps, oriented the same way.\n const linkageKey = (geneId: string) =>\n canonicalString(\n (cleanOf.get(geneId) ?? [])\n .map(({ step, carrierId }) => `${step.key}:${carrierId === step.childId ? '+' : '-'}`)\n .sort(compareCodeUnits),\n )\n const linkGroups = new Map<string, string[]>()\n for (const record of [...genes.values()].sort((a, b) => compareOrder(a.order, b.order))) {\n if (!cleanOf.has(record.geneId)) continue\n const key = linkageKey(record.geneId)\n appendTo(linkGroups, key, record.geneId)\n }\n\n const geneList: EditGene[] = [...genes.values()].map((record) => {\n const clean = cleanOf.get(record.geneId) ?? []\n const group = clean.length > 0 ? linkGroups.get(linkageKey(record.geneId))! : []\n const carriers = carriersOf.get(record.geneId)!\n const { credit, verdict } = credits.get(record.geneId)!\n return {\n geneId: record.geneId,\n kind: record.kind,\n path: record.path,\n lines: record.lines,\n text: record.text,\n introduced: record.introduced,\n dropped: record.dropped,\n edit: [...editsOf.get(record.geneId)![0]!].sort((a, b) =>\n compareOrder(genes.get(a)!.order, genes.get(b)!.order),\n ),\n carriers: [...carriers].filter((nodeId) => !invalid.has(nodeId)).length,\n invalidCarriers: [...carriers].filter((nodeId) => invalid.has(nodeId)).length,\n steps: {\n flips: flipCount.get(record.geneId) ?? 0,\n clean: clean.length,\n gained: clean.filter(({ step, carrierId }) => carrierId === step.childId).length,\n lost: clean.filter(({ step, carrierId }) => carrierId === step.parentId).length,\n },\n credit,\n verdict,\n linkage: group.length > 1 ? group[0]! : null,\n }\n })\n const verdictRank: Record<EditGeneVerdict, number> = {\n reusable: 0,\n harmful: 1,\n unresolved: 2,\n insufficient: 3,\n }\n geneList.sort(\n (a, b) =>\n verdictRank[a.verdict] - verdictRank[b.verdict] ||\n improvementLow(b.credit, sign) - improvementLow(a.credit, sign) ||\n gain(b.credit, sign) - gain(a.credit, sign) ||\n compareOrder(genes.get(a.geneId)!.order, genes.get(b.geneId)!.order),\n )\n const counts = emptyCounts()\n const editCounts = emptyCounts()\n for (const gene of geneList) {\n counts[gene.verdict] += 1\n // An edit is a linkage group; a gene with no clean step belongs to the\n // edit it was born in.\n const lead = gene.linkage ?? (gene.steps.clean === 0 ? gene.edit[0]! : gene.geneId)\n if (lead === gene.geneId) editCounts[gene.verdict] += 1\n }\n\n const interactions = interactionPairs({\n genes: geneList,\n cleanOf,\n carriersOf,\n unitMeansOf,\n limit: interactionGenes,\n sign,\n })\n const skillCandidates = skills(geneList, genes, header.subject, split)\n const lineage = lineageRows(state, nodes, byId, contents, carried)\n\n const isMeasured = (gene: EditGene) =>\n gene.credit.method === 'descriptive' || gene.credit.method === 'bootstrap'\n const measured = geneList.filter(isMeasured).length\n const measuredLeads = geneList.filter(\n (gene) => isMeasured(gene) && (gene.linkage ?? gene.geneId) === gene.geneId,\n )\n const expectedReusable = plain(\n Math.round(\n measuredLeads.reduce((sum, gene) => sum + chanceReusable(gene.credit.pairs), 0) * 1e6,\n ) / 1e6,\n )\n const top = geneList\n .filter((gene) => gene.verdict === 'reusable' && (gene.linkage ?? gene.geneId) === gene.geneId)\n .map((gene) => gene.geneId)\n const signal: EditCreditSignal =\n measured === 0\n ? {\n name: EDIT_CREDIT_SIGNAL,\n value: null,\n basis: `insufficient: no gene has ${DESCRIPTIVE_FROM} ${split} units on clean steps (${geneList.length} genes, ${measurable.length} measurable steps)`,\n top: [],\n }\n : {\n name: EDIT_CREDIT_SIGNAL,\n value: editCounts.reusable,\n basis: `independent edits pairedDeltaTest finds improve the objective on the ${split} split (${counts.reusable} genes), of ${measuredLeads.length} edits (${measured} genes) measured on ${DESCRIPTIVE_FROM} or more units; about ${expectedReusable.toFixed(2)} would be called reusable by chance with no true effect (unadjusted)`,\n top,\n }\n\n return {\n signal,\n data: {\n split,\n direction,\n edges: { lineage: lineageEdges, read: readEdges, unknown: unknownEdges },\n steps: { total: stepList.length, invalidEnd: stepList.length - measurable.length },\n nodes: {\n total: nodes.length,\n contentUnknown: [...contents.values()].filter((content) => !content.known).length,\n invalid: invalid.size,\n },\n genes: geneList,\n counts,\n editCounts,\n interactions,\n skillCandidates,\n chance: {\n measuredEdits: measuredLeads.length,\n expectedReusable,\n method: `per measured edit, the chance with no true effect that its verdict is reusable: the exact one-sided sign test's attained size at its unit count below ${BOOTSTRAP_GATE_MIN_N} units (at most ${(1 - CONFIDENCE) / 2}; the point-estimate condition only lowers it), the nominal ${(1 - CONFIDENCE) / 2} of the percentile bootstrap from ${BOOTSTRAP_GATE_MIN_N}; summed, so it is the expected number of false reusable edits if every edit had no effect`,\n },\n lineage,\n method: {\n estimator: EDIT_CREDIT_ESTIMATOR,\n credit: `per clean step (a parent and its child on which every change belongs to one edit that introduced the gene), the carrying side against the lacking side on each unit both scored; per unit, both sides averaged over those steps; ${DECISION_PAIRED_DELTA_STATISTIC} paired delta with a ${Math.round(CONFIDENCE * 100)}% percentile bootstrap (${RESAMPLES} resamples, seeded from cellSetDigest): none below 2 units, insufficient below ${DESCRIPTIVE_FROM}, a descriptive interval and exact one-sided sign p below ${BOOTSTRAP_GATE_MIN_N}, a decision-grade interval from ${BOOTSTRAP_GATE_MIN_N}; unscored cells are absent, never zero`,\n verdict: `pairedDeltaTest's own decision in each direction: reusable when it finds an improvement (below ${BOOTSTRAP_GATE_MIN_N} units an exact one-sided sign test at ${(1 - CONFIDENCE) / 2} with the point estimate on the better side; from ${BOOTSTRAP_GATE_MIN_N} the bootstrap interval above zero), harmful when it finds one in the other direction, unresolved otherwise, insufficient below ${DESCRIPTIVE_FROM} units`,\n interaction: `per unit, a gene's clean-step contrast where both ends carry the other gene minus where neither does, averaged over both directions; ${Math.round(CONFIDENCE * 100)}% percentile bootstrap (${RESAMPLES} resamples) for spread; exact two-sided sign test, Holm-adjusted over the pairs tested, flagged at ${INTERACTION_ALPHA}`,\n multiplicity:\n 'credit is not adjusted for the number of genes: it steers which edits to reuse and test next, as selection estimates steer spend, and claims nothing; interaction flags are Holm-adjusted because pairs grow with the square of the genes',\n selectionBias:\n 'a policy chooses a parent for its scores, so a parent is high by chance on the units it was chosen on: on a step where the child gained a gene the lacking side is that parent, and credit is biased toward harmful; where the child lost it, toward reusable. Only the sealed test split is free of this, so a reusable edit still needs a held-out test before it ships',\n },\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Content\n\nfunction nodeContent(options: EditCreditOptions, ref: SearchArtifactRef): NodeContent {\n const body = options.readArtifact(ref)\n if (body === undefined) return { known: false, reason: `artifact ${ref.role} unreadable` }\n const paths = new Map<string, PathText>()\n const record = body as { kind?: unknown; surface?: unknown }\n if (record && typeof record === 'object' && record.kind === 'mutable-surface') {\n const surface = record.surface as\n | string\n | { kind: 'components'; components: Record<string, string> }\n | { kind: 'code' }\n | undefined\n if (typeof surface === 'string') addText(paths, 'prompt', surface)\n else if (surface?.kind === 'components') {\n for (const name of Object.keys(surface.components).sort(compareCodeUnits)) {\n addText(paths, `component:${name}`, surface.components[name]!)\n }\n } else {\n return { known: false, reason: 'code surface: its patch bytes are not in the ledger' }\n }\n } else {\n flatten(body, '', paths)\n }\n const haystacks = new Map<string, string>()\n for (const [path, text] of paths) {\n haystacks.set(path, `\\n${text.norm.filter((line) => line.length > 0).join('\\n')}\\n`)\n }\n return { known: true, paths, haystacks }\n}\n\n/** JSON as text per location: a string's lines at its path, an array's\n * elements as lines at the array's path, any other value as one canonical\n * line. Array elements share a path, so an insertion does not renumber the\n * rest. */\nfunction flatten(value: unknown, path: string, paths: Map<string, PathText>): void {\n const at = path === '' ? '/' : path\n if (typeof value === 'string') {\n addText(paths, at, value)\n } else if (Array.isArray(value)) {\n for (const element of value) {\n addText(paths, at, typeof element === 'string' ? element : canonicalString(element))\n }\n } else if (value !== null && typeof value === 'object') {\n for (const key of Object.keys(value).sort(compareCodeUnits)) {\n const escaped = key.replaceAll('~', '~0').replaceAll('/', '~1')\n flatten((value as Record<string, unknown>)[key], `${path}/${escaped}`, paths)\n }\n } else {\n addText(paths, at, canonicalString(value))\n }\n}\n\nfunction addText(paths: Map<string, PathText>, path: string, text: string): void {\n const entry = paths.get(path) ?? { raw: [], norm: [] }\n for (const line of text.split(/\\r?\\n/)) {\n entry.raw.push(line)\n entry.norm.push(line.replace(/\\s+/g, ' ').trim())\n }\n paths.set(path, entry)\n}\n\nfunction carries(\n content: KnownContent,\n gene: { kind: 'insert' | 'delete'; path: string; needle: string },\n): boolean {\n const present = content.haystacks.get(gene.path)?.includes(gene.needle) ?? false\n return gene.kind === 'insert' ? present : !present\n}\n\nfunction locusOf(cut: { path: string; lines: readonly string[] }): string {\n return canonicalString([cut.path, cut.lines])\n}\n\n// ---------------------------------------------------------------------------\n// Genes\n\nfunction edgeCuts(parent: KnownContent, child: KnownContent): GeneCut[] {\n const cuts: GeneCut[] = []\n const paths = new Set([...parent.paths.keys(), ...child.paths.keys()])\n let position = 0\n for (const path of [...paths].sort(compareCodeUnits)) {\n const before = parent.paths.get(path) ?? { raw: [], norm: [] }\n const after = child.paths.get(path) ?? { raw: [], norm: [] }\n for (const run of changeRuns(before.norm, after.norm)) {\n for (const [kind, side, start, end] of [\n ['delete', before, run.aStart, run.aEnd],\n ['insert', after, run.bStart, run.bEnd],\n ] as const) {\n for (const [from, to] of paragraphs(side.norm, start, end)) {\n const lines = side.norm.slice(from, to).filter((line) => line.length > 0)\n if (lines.length === 0) continue\n cuts.push({\n kind,\n path,\n lines,\n needle: `\\n${lines.join('\\n')}\\n`,\n text: side.raw.slice(from, to).join('\\n').trim(),\n position: position++,\n })\n }\n }\n }\n }\n return cuts\n}\n\n/** Paragraph ranges of `lines[start, end)`, split at blank lines. */\nfunction paragraphs(lines: readonly string[], start: number, end: number): Array<[number, number]> {\n const ranges: Array<[number, number]> = []\n let from = -1\n for (let index = start; index < end; index++) {\n if (lines[index]!.length === 0) {\n if (from >= 0) ranges.push([from, index])\n from = -1\n } else if (from < 0) {\n from = index\n }\n }\n if (from >= 0) ranges.push([from, end])\n return ranges\n}\n\ninterface ChangeRun {\n aStart: number\n aEnd: number\n bStart: number\n bEnd: number\n}\n\n/** Maximal runs where `a[aStart, aEnd)` became `b[bStart, bEnd)`, from a\n * shortest edit script (Myers, 1986). */\nfunction changeRuns(a: readonly string[], b: readonly string[]): ChangeRun[] {\n let prefix = 0\n while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix += 1\n let suffix = 0\n while (\n suffix < a.length - prefix &&\n suffix < b.length - prefix &&\n a[a.length - 1 - suffix] === b[b.length - 1 - suffix]\n ) {\n suffix += 1\n }\n const innerA = a.slice(prefix, a.length - suffix)\n const innerB = b.slice(prefix, b.length - suffix)\n const runs: ChangeRun[] = []\n let i = 0\n let j = 0\n const flush = (toI: number, toJ: number) => {\n if (toI > i || toJ > j) {\n runs.push({ aStart: prefix + i, aEnd: prefix + toI, bStart: prefix + j, bEnd: prefix + toJ })\n }\n }\n for (const [mi, mj] of matches(innerA, innerB)) {\n flush(mi, mj)\n i = mi + 1\n j = mj + 1\n }\n flush(innerA.length, innerB.length)\n return runs\n}\n\n/** Matched index pairs of a shortest edit script, in increasing order. */\nfunction matches(a: readonly string[], b: readonly string[]): Array<[number, number]> {\n const n = a.length\n const m = b.length\n if (n === 0 || m === 0) return []\n const offset = n + m\n const v = new Int32Array(2 * offset + 2)\n const trace: Int32Array[] = []\n let done = false\n for (let d = 0; d <= n + m && !done; d++) {\n trace.push(v.slice())\n for (let k = -d; k <= d; k += 2) {\n let x =\n k === -d || (k !== d && v[k - 1 + offset]! < v[k + 1 + offset]!)\n ? v[k + 1 + offset]!\n : v[k - 1 + offset]! + 1\n let y = x - k\n while (x < n && y < m && a[x] === b[y]) {\n x += 1\n y += 1\n }\n v[k + offset] = x\n if (x >= n && y >= m) {\n done = true\n break\n }\n }\n }\n const pairs: Array<[number, number]> = []\n let x = n\n let y = m\n for (let d = trace.length - 1; d >= 0; d--) {\n const before = trace[d]!\n const k = x - y\n const prevK =\n k === -d || (k !== d && before[k - 1 + offset]! < before[k + 1 + offset]!) ? k + 1 : k - 1\n const prevX = before[prevK + offset]!\n const prevY = prevX - prevK\n while (x > prevX && y > prevY) {\n x -= 1\n y -= 1\n pairs.push([x, y])\n }\n if (d > 0) {\n x = prevX\n y = prevY\n }\n }\n return pairs.reverse()\n}\n\n// ---------------------------------------------------------------------------\n// Lineage\n\n/** Parents of an edge that precede its child in this search: the edge's\n * lineage. A re-proposal from the child itself or a later node adds none. */\nfunction lineageParents(\n state: SearchStateView,\n edge: SearchEdgeRecordedEvent,\n child: SearchNode,\n byId: ReadonlyMap<string, SearchNode>,\n): string[] {\n const parents: string[] = []\n for (const parent of edge.parents) {\n if (parent.searchId !== state.searchId) continue\n const node = byId.get(parent.nodeId)\n if (node && node.ordinal < child.ordinal && !parents.includes(node.nodeId)) {\n parents.push(node.nodeId)\n }\n }\n return parents\n}\n\nfunction lineageRows(\n state: SearchStateView,\n nodes: readonly SearchNode[],\n byId: ReadonlyMap<string, SearchNode>,\n contents: ReadonlyMap<string, NodeContent>,\n carried: ReadonlyMap<string, string[]>,\n): EditLineageRow[] {\n const rows: EditLineageRow[] = []\n const placed = new Set<string>()\n const visit = (root: SearchNode) => {\n const stack = [root]\n while (stack.length > 0) {\n const node = stack.pop()!\n if (placed.has(node.nodeId)) continue\n placed.add(node.nodeId)\n const firstEdge = node.edgeIds[0] ? state.edge(node.edgeIds[0]) : undefined\n rows.push({\n nodeId: node.nodeId,\n ordinal: node.ordinal,\n depth: node.depth,\n primaryParentId: node.primaryParentId,\n parents: node.parents\n .filter((parent) => parent.searchId === state.searchId)\n .map((parent) => parent.nodeId),\n operator: firstEdge?.operator ?? null,\n status: node.status,\n carries: [...(carried.get(node.nodeId) ?? [])].sort(compareCodeUnits),\n contentKnown: contents.get(node.nodeId)!.known,\n })\n const children = node.children\n .map((id) => byId.get(id)!)\n .filter((child) => child.primaryParentId === node.nodeId)\n .sort((a, b) => b.ordinal - a.ordinal)\n stack.push(...children)\n }\n }\n for (const node of nodes) if (node.primaryParentId === null) visit(node)\n for (const node of nodes) visit(node)\n return rows\n}\n\n// ---------------------------------------------------------------------------\n// Statistics\n\n/**\n * The paired contrast of per-unit carrier means against per-unit lacking\n * means, staged and oriented exactly as `estimateNodeFromCells` stages and\n * orients a node against another, with the verdict `pairedDeltaTest` itself\n * would reach in each direction: below 20 units the exact one-sided sign test\n * at α = 0.025 and a point estimate on the same side, from 20 the bootstrap\n * interval clear of zero.\n */\nfunction pairedEstimate(input: {\n against: string\n split: SearchSplit\n direction: 'maximize' | 'minimize'\n units: number\n carrier: number[]\n lacking: number[]\n cellSetDigest: NodeEstimate['cellSetDigest']\n}): { credit: NodeEstimate; verdict: EditGeneVerdict } {\n const pairs = input.carrier.length\n const method = searchEstimateMethod(pairs)\n const base = {\n against: input.against,\n split: input.split,\n units: input.units,\n pairs,\n method,\n cellSetDigest: input.cellSetDigest,\n estimator: EDIT_CREDIT_ESTIMATOR,\n }\n if (method === 'none') {\n return {\n credit: { ...base, delta: null, interval: null, exactSignP: null, indeterminate: false },\n verdict: 'insufficient',\n }\n }\n // The test's `after - before` is the improvement: carrier minus lacking\n // when larger is better, lacking minus carrier when smaller is.\n const maximize = input.direction === 'maximize'\n const before = maximize ? input.lacking : input.carrier\n const after = maximize ? input.carrier : input.lacking\n const options = {\n statistic: DECISION_PAIRED_DELTA_STATISTIC,\n confidence: CONFIDENCE,\n resamples: RESAMPLES,\n seed: seedFromDigest(input.cellSetDigest),\n }\n const better = pairedDeltaTest(before, after, options)\n const worse = pairedDeltaTest(after, before, options)\n const { mean, low, high } = better.bootstrap\n const indeterminate = better.indeterminate\n const spread = (method === 'descriptive' || method === 'bootstrap') && !indeterminate\n const credit: NodeEstimate = {\n ...base,\n delta: plain(maximize ? mean : -mean),\n interval: spread ? (maximize ? [plain(low), plain(high)] : [plain(-high), plain(-low)]) : null,\n exactSignP: method === 'descriptive' && !indeterminate ? better.pValue : null,\n indeterminate,\n }\n const verdict: EditGeneVerdict =\n method === 'insufficient'\n ? 'insufficient'\n : better.significant\n ? 'reusable'\n : worse.significant\n ? 'harmful'\n : 'unresolved'\n return { credit, verdict }\n}\n\n/** The chance, with no true effect, that the verdict on `pairs` units is\n * reusable: the exact sign test's attained size (the upper tail at the\n * smallest positive count that clears α) below the bootstrap gate, the\n * percentile bootstrap's nominal one-sided α from it. */\nconst chanceReusable = (() => {\n const alpha = (1 - CONFIDENCE) / 2\n const cache = new Map<number, number>()\n return (pairs: number): number => {\n if (pairs < DESCRIPTIVE_FROM) return 0\n if (pairs >= BOOTSTRAP_GATE_MIN_N) return alpha\n const cached = cache.get(pairs)\n if (cached !== undefined) return cached\n let size = 0\n for (let positive = 0; positive <= pairs; positive++) {\n const signs = Array.from({ length: pairs }, (_, index) => (index < positive ? 1 : -1))\n const p = pairedSignTest(signs, 'greater').pValue\n if (p <= alpha) {\n size = p\n break\n }\n }\n cache.set(pairs, size)\n return size\n }\n})()\n\n/** The worse end of the interval, as an improvement; -Infinity without one. */\nfunction improvementLow(credit: NodeEstimate, sign: number): number {\n if (credit.interval === null) return Number.NEGATIVE_INFINITY\n return sign > 0 ? credit.interval[0] : -credit.interval[1]\n}\n\nfunction gain(credit: NodeEstimate, sign: number): number {\n return credit.delta === null ? Number.NEGATIVE_INFINITY : sign * credit.delta\n}\n\nfunction interactionPairs(input: {\n genes: readonly EditGene[]\n cleanOf: ReadonlyMap<string, ReadonlyArray<{ step: Step; carrierId: string; lackingId: string }>>\n carriersOf: ReadonlyMap<string, ReadonlySet<string>>\n unitMeansOf: (nodeId: string) => ReadonlyMap<string, number>\n limit: number\n sign: number\n}): EditCreditData['interactions'] {\n // One member per linkage group: linked genes have the same clean steps, so\n // every pair across two groups repeats one contrast.\n const seenGroups = new Set<string>()\n const considered = [...input.genes]\n .filter((gene) => {\n const group = gene.linkage ?? gene.geneId\n if (seenGroups.has(group)) return false\n seenGroups.add(group)\n return gene.credit.pairs >= DESCRIPTIVE_FROM\n })\n .sort((a, b) => b.credit.pairs - a.credit.pairs || compareCodeUnits(a.geneId, b.geneId))\n .slice(0, input.limit)\n\n /** Per unit, the mean clean-step contrast of `geneId` over `steps`. */\n const contrasts = (\n steps: ReadonlyArray<{ carrierId: string; lackingId: string }>,\n ): Map<string, number> => {\n const sums = new Map<string, { sum: number; count: number }>()\n for (const { carrierId, lackingId } of steps) {\n const lacking = input.unitMeansOf(lackingId)\n for (const [unitId, carrierMean] of input.unitMeansOf(carrierId)) {\n const lackingMean = lacking.get(unitId)\n if (lackingMean === undefined) continue\n const entry = sums.get(unitId) ?? { sum: 0, count: 0 }\n entry.sum += carrierMean - lackingMean\n entry.count += 1\n sums.set(unitId, entry)\n }\n }\n return new Map([...sums].map(([unitId, entry]) => [unitId, entry.sum / entry.count]))\n }\n /** `geneId`'s clean steps split by whether both ends carry `other`. */\n const split = (geneId: string, other: string) => {\n const carriers = input.carriersOf.get(other)!\n const steps = input.cleanOf.get(geneId) ?? []\n const withOther = steps.filter(\n ({ step }) => carriers.has(step.parentId) && carriers.has(step.childId),\n )\n const withoutOther = steps.filter(\n ({ step }) => !carriers.has(step.parentId) && !carriers.has(step.childId),\n )\n return { withOther, withoutOther }\n }\n\n const pairs: EditInteraction[] = []\n for (let i = 0; i < considered.length; i++) {\n for (let j = i + 1; j < considered.length; j++) {\n const first = considered[i]!\n const second = considered[j]!\n if (first.edit.includes(second.geneId) || second.edit.includes(first.geneId)) continue\n const firstSplit = split(first.geneId, second.geneId)\n const secondSplit = split(second.geneId, first.geneId)\n const steps = {\n firstWithSecond: firstSplit.withOther.length,\n firstWithoutSecond: firstSplit.withoutOther.length,\n secondWithFirst: secondSplit.withOther.length,\n secondWithoutFirst: secondSplit.withoutOther.length,\n }\n const directions = [firstSplit, secondSplit].filter(\n (direction) => direction.withOther.length > 0 && direction.withoutOther.length > 0,\n )\n if (directions.length === 0) continue\n const perUnit = new Map<string, { sum: number; count: number }>()\n for (const direction of directions) {\n const withMeans = contrasts(direction.withOther)\n const withoutMeans = contrasts(direction.withoutOther)\n for (const [unitId, withMean] of withMeans) {\n const withoutMean = withoutMeans.get(unitId)\n if (withoutMean === undefined) continue\n const entry = perUnit.get(unitId) ?? { sum: 0, count: 0 }\n entry.sum += withMean - withoutMean\n entry.count += 1\n perUnit.set(unitId, entry)\n }\n }\n const values = [...perUnit.keys()]\n .sort(compareCodeUnits)\n .map((unitId) => perUnit.get(unitId)!.sum / perUnit.get(unitId)!.count)\n pairs.push(interactionEstimate([first.geneId, second.geneId], steps, values, input.sign))\n }\n }\n const tested = pairs.filter((pair) => pair.signP !== null)\n const adjusted = holm(\n tested.map((pair) => pair.signP!),\n INTERACTION_ALPHA,\n )\n tested.forEach((pair, index) => {\n pair.adjustedP = adjusted.adjusted[index]!\n pair.interacting = adjusted.significant[index]!\n })\n pairs.sort(\n (a, b) =>\n Number(b.interacting) - Number(a.interacting) ||\n (a.adjustedP ?? 2) - (b.adjustedP ?? 2) ||\n b.units - a.units ||\n compareCodeUnits(a.genes.join(), b.genes.join()),\n )\n return {\n genesConsidered: considered.length,\n pairsWithContexts: pairs.length,\n pairsTested: tested.length,\n alpha: INTERACTION_ALPHA,\n correction: 'holm',\n pairs,\n }\n}\n\nfunction interactionEstimate(\n genes: [string, string],\n steps: EditInteraction['steps'],\n values: number[],\n sign: number,\n): EditInteraction {\n const units = values.length\n const method = searchEstimateMethod(units)\n const base = { genes, steps, units, method, adjustedP: null, interacting: false }\n if (method === 'none') {\n return {\n ...base,\n interaction: null,\n interval: null,\n indeterminate: false,\n signP: null,\n synergy: null,\n }\n }\n const interaction = plain(values.reduce((sum, value) => sum + value, 0) / units)\n if (method === 'insufficient') {\n return {\n ...base,\n interaction,\n interval: null,\n indeterminate: false,\n signP: null,\n synergy: sign * interaction > 0,\n }\n }\n const zeros = values.map(() => 0)\n const test = pairedDeltaTest(zeros, values, {\n statistic: DECISION_PAIRED_DELTA_STATISTIC,\n confidence: CONFIDENCE,\n resamples: RESAMPLES,\n seed: seedFromDigest(hashCanonical({ genes, values })),\n })\n const indeterminate = test.indeterminate\n const greater = pairedSignTest(values, 'greater').pValue\n const less = pairedSignTest(values, 'less').pValue\n return {\n ...base,\n interaction,\n interval: indeterminate ? null : [plain(test.bootstrap.low), plain(test.bootstrap.high)],\n indeterminate,\n signP: indeterminate ? null : Math.min(1, 2 * Math.min(greater, less)),\n synergy: sign * interaction > 0,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Skills\n\nfunction skills(\n genes: readonly EditGene[],\n records: ReadonlyMap<string, GeneRecord>,\n subject: string,\n split: SearchSplit,\n): EditSkillCandidate[] {\n const byGroup = new Map<string, EditGene[]>()\n for (const gene of genes) {\n if (gene.verdict !== 'reusable' || gene.kind !== 'insert') continue\n const group = gene.linkage ?? gene.geneId\n appendTo(byGroup, group, gene)\n }\n const candidates: EditSkillCandidate[] = []\n for (const members of byGroup.values()) {\n members.sort((a, b) => compareOrder(records.get(a.geneId)!.order, records.get(b.geneId)!.order))\n const lead = members[0]!\n const name = `edit-${lead.geneId.slice('gene_'.length, 'gene_'.length + 12)}`\n const content = [\n '---',\n `name: ${name}`,\n `description: ${JSON.stringify(\n `Instructions a ${subject} search kept: the edit to ${lead.path} whose carriers scored better than the nodes without it on the ${split} split.`,\n )}`,\n '---',\n '',\n members.map((gene) => gene.text).join('\\n\\n'),\n '',\n ].join('\\n')\n candidates.push({\n resource: defineInlineResource(name, content) as Extract<\n AgentProfileResourceRef,\n { kind: 'inline' }\n >,\n improveOptions: { surface: 'skills', skills: { resourceName: name } },\n genes: members.map((gene) => gene.geneId),\n path: lead.path,\n credit: lead.credit,\n })\n }\n return candidates\n}\n\n// ---------------------------------------------------------------------------\n// Text\n\n/** The lens as compact text: what `agent-eval search show --edit-credit`\n * prints and a proposer can read. */\nexport function editCreditText(result: EditCreditResult, options: { limit?: number } = {}): string {\n const limit = options.limit ?? 10\n const { data, signal } = result\n const unknown = Object.entries(data.edges.unknown)\n .map(([reason, count]) => `${count} ${reason}`)\n .join(', ')\n const lines = [\n `edit credit — ${data.genes.length} genes from ${data.edges.read} of ${data.edges.lineage} lineage edges, ${data.steps.total - data.steps.invalidEnd} measurable steps (${data.split} split, ${data.direction})`,\n ` genes: reusable ${data.counts.reusable} · harmful ${data.counts.harmful} · unresolved ${data.counts.unresolved} · insufficient ${data.counts.insufficient}`,\n ` edits: reusable ${data.editCounts.reusable} · harmful ${data.editCounts.harmful} · unresolved ${data.editCounts.unresolved} · insufficient ${data.editCounts.insufficient}`,\n ` signal ${signal.name} = ${signal.value ?? 'null'} (${signal.basis})${signal.top.length > 0 ? `; top: ${signal.top.slice(0, 5).join(', ')}` : ''}`,\n ]\n if (unknown.length > 0) lines.push(` edges without content: ${unknown}`)\n if (data.nodes.invalid > 0) {\n lines.push(\n ` ${data.nodes.invalid} invalid node(s): ${data.steps.invalidEnd} step(s) excluded from every contrast`,\n )\n }\n lines.push('', 'Genes (carrying vs lacking side of each clean lineage step):')\n if (data.genes.length === 0) lines.push(' none')\n for (const gene of data.genes.slice(0, limit)) {\n const reproposed = gene.introduced.length > 1 ? ` · introduced ${gene.introduced.length}×` : ''\n const dropped = gene.dropped > 0 ? ` · dropped ${gene.dropped}×` : ''\n const linked =\n gene.linkage && gene.linkage !== gene.geneId ? ` · linked to ${gene.linkage}` : ''\n const invalid = gene.invalidCarriers > 0 ? ` · ${gene.invalidCarriers} invalid carrier(s)` : ''\n lines.push(\n ` ${gene.geneId} ${gene.verdict} ${gene.kind} ${gene.path} \"${excerpt(gene.lines)}\"`,\n ` ${gene.steps.clean} clean of ${gene.steps.flips} step(s) (+${gene.steps.gained}/−${gene.steps.lost}) · ${formatEstimate(gene.credit)}${reproposed}${dropped}${linked}${invalid}`,\n )\n }\n if (data.genes.length > limit) lines.push(` … ${data.genes.length - limit} more`)\n const { interactions } = data\n lines.push(\n '',\n `Interactions: ${interactions.pairsTested} pair(s) tested of ${interactions.pairsWithContexts} with both contexts, among ${interactions.genesConsidered} genes (Holm, α=${interactions.alpha}):`,\n )\n const shown = interactions.pairs.filter((pair) => pair.signP !== null).slice(0, limit)\n if (shown.length === 0) lines.push(' none testable')\n for (const pair of shown) {\n const interval = pair.interval\n ? ` [${pair.interval[0].toFixed(4)}, ${pair.interval[1].toFixed(4)}]`\n : ''\n lines.push(\n ` ${pair.genes[0]} × ${pair.genes[1]}: ${pair.interacting ? 'INTERACTING' : 'no flag'} ${signed(pair.interaction)}${interval} on ${pair.units} units, sign p=${pair.signP!.toPrecision(3)}, Holm p=${pair.adjustedP!.toPrecision(3)}`,\n )\n }\n lines.push('', `Skill candidates (agent-runtime improve surface 'skills'):`)\n if (data.skillCandidates.length === 0) lines.push(' none')\n for (const candidate of data.skillCandidates.slice(0, limit)) {\n lines.push(\n ` ${candidate.resource.name}: ${candidate.genes.length} gene(s) at ${candidate.path} · ${formatEstimate(candidate.credit)}`,\n )\n }\n return lines.join('\\n')\n}\n\nfunction excerpt(lines: readonly string[]): string {\n const text = lines.join(' ⏎ ')\n return text.length <= 72 ? text : `${text.slice(0, 71)}…`\n}\n\nfunction signed(value: number | null): string {\n if (value === null) return 'null'\n return `${value >= 0 ? '+' : ''}${value.toFixed(4)}`\n}\n\nfunction formatEstimate(estimate: NodeEstimate): string {\n const units = `${estimate.pairs} unit${estimate.pairs === 1 ? '' : 's'}`\n if (estimate.method === 'none') return `unknown (${units})`\n if (estimate.indeterminate) return `no measurable difference (indeterminate, ${units})`\n const delta = `Δ=${signed(estimate.delta)}`\n if (estimate.method === 'insufficient') {\n return `${delta} (${estimate.pairs} of ${DESCRIPTIVE_FROM} units, insufficient)`\n }\n const interval = estimate.interval\n ? ` [${estimate.interval[0].toFixed(4)}, ${estimate.interval[1].toFixed(4)}]`\n : ''\n if (estimate.method === 'descriptive') {\n const p = estimate.exactSignP === null ? 'null' : estimate.exactSignP.toPrecision(3)\n return `${delta}${interval} descriptive, sign p=${p} (${units})`\n }\n return `${delta}${interval} bootstrap (${units})`\n}\n\n// ---------------------------------------------------------------------------\n\nfunction emptyCounts(): Record<EditGeneVerdict, number> {\n return { reusable: 0, harmful: 0, unresolved: 0, insufficient: 0 }\n}\n\nfunction appendTo<T>(map: Map<string, T[]>, key: string, value: T): void {\n const list = map.get(key)\n if (list) list.push(value)\n else map.set(key, [value])\n}\n\nfunction memo<T>(compute: (key: string) => T): (key: string) => T {\n const cache = new Map<string, T>()\n return (key) => {\n let value = cache.get(key)\n if (value === undefined) {\n value = compute(key)\n cache.set(key, value)\n }\n return value\n }\n}\n\nfunction compareOrder(left: [number, number], right: [number, number]): number {\n return left[0] - right[0] || left[1] - right[1]\n}\n\n/** Canonical JSON has one zero; never hand it a negative one. */\nfunction plain(value: number): number {\n return value === 0 ? 0 : value\n}\n","/**\n * `front(state, axes)`: the Pareto front over a node's score and its known\n * cost per cell, with room for caller-declared axes (search-tree-design §12).\n *\n * Reuses the existing frontier primitive (`../../pareto`, already the parent\n * selector behind `crowdedFrontierParent` in `search-policy.ts`) rather than\n * a second dominance implementation.\n *\n * The cost axis is the node's cost per attempted cell on the ranking split,\n * not its total spend: an allocator gives a node more cells as it advances,\n * so a total would rank a node by how far it was measured, and a node pruned\n * after its screen would look cheap only for having run fewer cells. A node\n * enters the frontier only when its score rests on 2 or more units (one unit\n * is no estimate, §6.4), every attempted cell on the split has a known cost\n * (an unknown cost is never floored to its known partial or imputed), and it\n * was not decided `invalid` (a judge integrity or admission failure, whose\n * score a reward hack may have produced; such a node never becomes a parent,\n * §6.6).\n */\n\nimport { searchEstimateMethod } from '../../campaign/estimate-node'\nimport type { SearchEstimateMethod } from '../../campaign/search-ledger-types'\nimport type { SearchStateView } from '../../campaign/search-state'\nimport { type Objective, paretoFrontier } from '../../pareto'\nimport { rankingSplit } from './shared'\n\nexport interface FrontExtraAxis {\n name: string\n direction: 'maximize' | 'minimize'\n /** Reads the axis value for one node from the same state the lens holds.\n * Returning a non-finite number excludes the node from this axis's frontier\n * pass the same way an unknown score or cost does. */\n value(state: SearchStateView, nodeId: string): number\n}\n\nexport interface FrontRow {\n nodeId: string\n /** Mean per-unit score on the ranking split, in the objective's own units;\n * null when the node has no scored cell there. */\n score: number | null\n /** Units `score` averages over, and the method that many units supports. */\n units: number\n method: SearchEstimateMethod\n /** Known cost per attempted cell on the ranking split; null when any of\n * those cells has an unknown cost, or none was attempted. */\n costPerCellUsd: number | null\n /** Everything the node has spent so far, in every split: how far it was\n * measured, not what it costs to run. */\n knownCostUsd: number\n /** False when any of the node's cells has an unknown-cost attempt: its true\n * spend may be higher than `knownCostUsd`. */\n costKnown: boolean\n /** True only for an eligible node that no other eligible node dominates on\n * every declared axis. */\n onFront: boolean\n /** Why the node is off every frontier pass; null when it is eligible. */\n excluded: FrontExclusion | null\n}\n\nexport type FrontExclusion = 'invalid' | 'unscored' | 'one-unit' | 'unknown-cost' | 'extra-axis'\n\nexport interface FrontData {\n split: 'train' | 'selection'\n axes: string[]\n rows: FrontRow[]\n frontierSize: number\n /** Rows excluded from every frontier pass. */\n excludedCount: number\n /** `excludedCount` by reason. */\n exclusions: Record<FrontExclusion, number>\n}\n\nexport interface FrontOptions {\n split?: 'train' | 'selection'\n axes?: FrontExtraAxis[]\n}\n\n/** nodeId → 1 on the frontier, 0 off it. Every node appears; an excluded\n * node reads 0, same as a dominated one, because \"on the front\" is the only\n * claim this signal makes. */\nexport type FrontSignal = Record<string, number>\n\nexport function front(\n state: SearchStateView,\n options: FrontOptions = {},\n): { data: FrontData; signal: { name: string; value: FrontSignal } } {\n const split = options.split ?? rankingSplit(state)\n const direction = state.header?.objective.direction ?? 'maximize'\n const extraAxes = options.axes ?? []\n\n const rows = state.nodes().map((node) => {\n const units = state.unitScores(node.nodeId, split)\n const score = units.length > 0 ? units.reduce((sum, u) => sum + u.mean, 0) / units.length : null\n let attempted = 0\n let spent = 0\n let known = true\n for (const cell of state.cells({ nodeId: node.nodeId })) {\n if (cell.split !== split || cell.attempts === 0) continue\n attempted += 1\n spent += cell.spentUsd\n if (!cell.costKnown) known = false\n }\n const extra = extraAxes.map((axis) => axis.value(state, node.nodeId))\n const costPerCellUsd = known && attempted > 0 ? spent / attempted : null\n const excluded: FrontExclusion | null =\n node.status === 'invalid'\n ? 'invalid'\n : score === null\n ? 'unscored'\n : units.length < 2\n ? 'one-unit'\n : costPerCellUsd === null\n ? 'unknown-cost'\n : extra.every((value) => Number.isFinite(value))\n ? null\n : 'extra-axis'\n return {\n nodeId: node.nodeId,\n score,\n units: units.length,\n method: searchEstimateMethod(units.length),\n costPerCellUsd,\n knownCostUsd: node.spend.knownUsd,\n costKnown: node.spend.unknownCostCells === 0,\n excluded,\n extra,\n }\n })\n\n type Eligible = (typeof rows)[number] & { score: number; costPerCellUsd: number }\n const eligible = rows.filter((row): row is Eligible => row.excluded === null)\n\n const objectives: Objective<Eligible>[] = [\n { name: 'score', direction, value: (row) => row.score },\n { name: 'costPerCellUsd', direction: 'minimize', value: (row) => row.costPerCellUsd },\n ...extraAxes.map(\n (axis, index): Objective<Eligible> => ({\n name: axis.name,\n direction: axis.direction,\n value: (row) => row.extra[index]!,\n }),\n ),\n ]\n\n const frontierIds =\n eligible.length > 0\n ? new Set(paretoFrontier(eligible, objectives).frontier.map((r) => r.nodeId))\n : new Set<string>()\n\n const exclusions: Record<FrontExclusion, number> = {\n invalid: 0,\n unscored: 0,\n 'one-unit': 0,\n 'unknown-cost': 0,\n 'extra-axis': 0,\n }\n const outRows: FrontRow[] = rows.map(({ extra: _extra, ...row }) => {\n if (row.excluded) exclusions[row.excluded] += 1\n return { ...row, onFront: frontierIds.has(row.nodeId) }\n })\n\n const signalValue: FrontSignal = {}\n for (const row of outRows) signalValue[row.nodeId] = row.onFront ? 1 : 0\n\n return {\n data: {\n split,\n axes: objectives.map((o) => o.name),\n rows: outRows,\n frontierSize: frontierIds.size,\n excludedCount: rows.length - eligible.length,\n exclusions,\n },\n signal: { name: 'front.membership', value: signalValue },\n }\n}\n","/**\n * What the geometry lenses (`landscape`, `skillManifold`) share beyond\n * `./shared`: a signal that states its method and sample, and the nodes whose\n * screen finished.\n *\n * A lens is a pure function of a `SearchStateView` (search-tree design §12).\n * It returns JSON for a view (Intelligence renders it; `agent-eval search\n * show` prints it as text) and one named numeric signal that a `SearchPolicy`\n * or an allocator can read, so what a person sees is what the climber uses.\n * A lens never renders, never reads a blob or a clock, and never imputes a\n * score or a cost: a value the ledger cannot support is null, with the reason.\n */\n\nimport type { SearchStateView } from '../../campaign/search-state'\nimport { medianInPlace } from '../../statistics/internal'\nimport type { LensResult, LensSignal } from './shared'\n\n/** The one number a geometry lens exposes to policies: the shared\n * `LensSignal`, with the noise model and sample it rests on. */\nexport interface GeometrySignal extends LensSignal<number | null> {\n /** What the value is about when it names one thing, for example the unit\n * `nextUnit` recommends; null otherwise. */\n subject: string | null\n /** How the value is computed, including its noise model. */\n method: string\n /** The sample the value rests on, in the unit `method` names. */\n n: number\n /** Why `value` is null; null when it is not. */\n insufficient: string | null\n}\n\nexport interface GeometryLensResult<TData> extends LensResult<TData, number | null> {\n /** The lens name, for example `landscape`. */\n lens: string\n searchId: string\n /** The ledger position the lens read: the head's sequence, or -1 before any entry. */\n sequence: number\n signal: GeometrySignal\n}\n\n/** Attempts the kernel gives a retryable errored cell by default. */\nexport const DEFAULT_MAX_ATTEMPTS = 3\n\n/**\n * Nodes whose screen finished, in registration order, root first: the\n * ledger's reading of the kernel's `screened` list. A node counts once it is\n * not decided invalid, has an edge, and every cell it was allocated outside a\n * rung or the claim can no longer run (scored, final, cancelled, or errored\n * with no attempt left). Cells a rung opened later do not un-screen it.\n */\nexport function screenedNodes(\n state: SearchStateView,\n options: { maxAttempts?: number } = {},\n): string[] {\n const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS\n const screened: string[] = []\n for (const node of state.nodes()) {\n if (node.status === 'invalid' || node.edgeIds.length === 0) continue\n let allocated = 0\n let open = false\n for (const cell of state.cells({ nodeId: node.nodeId })) {\n if (cell.stage === 'rung' || cell.stage === 'claim') continue\n allocated += 1\n const done =\n cell.final ||\n cell.cancelled !== null ||\n (cell.outcome === 'errored' && cell.attempts >= maxAttempts)\n if (!done) {\n open = true\n break\n }\n }\n if (allocated > 0 && !open) screened.push(node.nodeId)\n }\n return screened\n}\n\n/** The head's sequence, or -1 before the first entry. */\nexport function headSequence(state: SearchStateView): number {\n return state.head?.sequence ?? -1\n}\n\n/** Rounded for JSON a person reads; 9 decimals keep the bits a renderer\n * needs and drop float noise. */\nexport function round9(value: number): number {\n const rounded = Math.round(value * 1e9) / 1e9\n return rounded === 0 ? 0 : rounded\n}\n\nexport function median(values: readonly number[]): number | null {\n return values.length === 0 ? null : medianInPlace([...values])\n}\n\n/** At most `cap` items, evenly spaced by position: a deterministic sample\n * that keeps a quadratic step bounded on a large search. */\nexport function evenSample<T>(items: readonly T[], cap: number): T[] {\n if (items.length <= cap) return [...items]\n return Array.from({ length: cap }, (_, index) => items[Math.floor((index * items.length) / cap)]!)\n}\n\nexport function positiveInteger(owner: string, name: string, value: number): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new TypeError(`${owner}: ${name} must be a positive integer, got ${String(value)}`)\n }\n return value\n}\n\nexport function plural(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? '' : 's'}`\n}\n","/**\n * Cholesky factorization and solves for small symmetric positive-definite\n * systems (Golub and Van Loan, Matrix Computations, 4th ed., §4.2), the\n * ridge normal equations the skill-manifold lens solves once per row and\n * column of each alternating least-squares sweep.\n */\n\n/** The lower-triangular L with `matrix = L Lᵀ`, or null when the matrix is\n * not numerically positive definite. */\nexport function cholesky(matrix: readonly (readonly number[])[]): number[][] | null {\n const n = matrix.length\n const lower = Array.from({ length: n }, () => new Array<number>(n).fill(0))\n for (let j = 0; j < n; j++) {\n let diagonal = matrix[j]![j]!\n for (let k = 0; k < j; k++) diagonal -= lower[j]![k]! ** 2\n if (!(diagonal > 0) || !Number.isFinite(diagonal)) return null\n const pivot = Math.sqrt(diagonal)\n lower[j]![j] = pivot\n for (let i = j + 1; i < n; i++) {\n let value = matrix[i]![j]!\n for (let k = 0; k < j; k++) value -= lower[i]![k]! * lower[j]![k]!\n lower[i]![j] = value / pivot\n }\n }\n return lower\n}\n\n/** Solves `L Lᵀ x = b` for x given the Cholesky factor L. */\nexport function choleskySolve(\n lower: readonly (readonly number[])[],\n b: readonly number[],\n): number[] {\n const n = lower.length\n const y = new Array<number>(n).fill(0)\n for (let i = 0; i < n; i++) {\n let value = b[i]!\n for (let k = 0; k < i; k++) value -= lower[i]![k]! * y[k]!\n y[i] = value / lower[i]![i]!\n }\n const x = new Array<number>(n).fill(0)\n for (let i = n - 1; i >= 0; i--) {\n let value = y[i]!\n for (let k = i + 1; k < n; k++) value -= lower[k]![i]! * x[k]!\n x[i] = value / lower[i]![i]!\n }\n return x\n}\n\n/** The inverse of a symmetric positive-definite matrix from its factor. */\nexport function choleskyInverse(lower: readonly (readonly number[])[]): number[][] {\n const n = lower.length\n const columns = Array.from({ length: n }, (_, j) =>\n choleskySolve(\n lower,\n Array.from({ length: n }, (_, i) => (i === j ? 1 : 0)),\n ),\n )\n return Array.from({ length: n }, (_, i) => columns.map((column) => column[i]!))\n}\n","/**\n * Eigendecomposition of a small real symmetric matrix by cyclic Jacobi\n * rotations (Golub and Van Loan, Matrix Computations, 4th ed., §8.5).\n *\n * Jacobi is exact to rounding for symmetric input and needs no pivoting, so\n * the same matrix gives the same bits on every platform that follows IEEE 754\n * double arithmetic. It costs O(n³) per sweep and converges in a few sweeps,\n * which suits the matrices the search lenses decompose: landmark distance\n * matrices of at most a few dozen rows and unit-by-unit Gram matrices.\n */\n\nexport interface SymmetricEigen {\n /** Eigenvalues, largest first. */\n values: number[]\n /** `vectors[k]` is the unit eigenvector of `values[k]`. Its sign is fixed so\n * that its entry of largest magnitude is positive (the earliest such entry\n * on a tie), which makes the output deterministic. */\n vectors: number[][]\n}\n\nconst MAX_SWEEPS = 100\n\n/** Eigenvalues and eigenvectors of a symmetric matrix, largest value first. */\nexport function symmetricEigen(matrix: readonly (readonly number[])[]): SymmetricEigen {\n const n = matrix.length\n const a = matrix.map((row, index) => {\n if (row.length !== n) {\n throw new RangeError(`symmetricEigen: row ${index} has ${row.length} entries, expected ${n}`)\n }\n return row.map((value) => {\n if (!Number.isFinite(value)) throw new RangeError('symmetricEigen: entries must be finite')\n return value\n })\n })\n for (let i = 0; i < n; i++) {\n for (let j = i + 1; j < n; j++) {\n const scale = Math.max(1, Math.abs(a[i]![j]!), Math.abs(a[j]![i]!))\n if (Math.abs(a[i]![j]! - a[j]![i]!) > 1e-9 * scale) {\n throw new RangeError(`symmetricEigen: the matrix is not symmetric at (${i}, ${j})`)\n }\n }\n }\n const v: number[][] = Array.from({ length: n }, (_, i) =>\n Array.from({ length: n }, (_, j) => (i === j ? 1 : 0)),\n )\n let total = 0\n for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) total += a[i]![j]! ** 2\n const tolerance = 1e-24 * Math.max(total, Number.MIN_VALUE)\n for (let sweep = 0; sweep < MAX_SWEEPS; sweep++) {\n let off = 0\n for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) off += a[i]![j]! ** 2\n if (off <= tolerance) break\n for (let p = 0; p < n; p++) {\n for (let q = p + 1; q < n; q++) {\n const apq = a[p]![q]!\n if (apq === 0) continue\n const theta = (a[q]![q]! - a[p]![p]!) / (2 * apq)\n const t = Math.sign(theta || 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1))\n const c = 1 / Math.sqrt(t * t + 1)\n const s = t * c\n for (let k = 0; k < n; k++) {\n const akp = a[k]![p]!\n const akq = a[k]![q]!\n a[k]![p] = c * akp - s * akq\n a[k]![q] = s * akp + c * akq\n }\n for (let k = 0; k < n; k++) {\n const apk = a[p]![k]!\n const aqk = a[q]![k]!\n a[p]![k] = c * apk - s * aqk\n a[q]![k] = s * apk + c * aqk\n }\n for (let k = 0; k < n; k++) {\n const vkp = v[k]![p]!\n const vkq = v[k]![q]!\n v[k]![p] = c * vkp - s * vkq\n v[k]![q] = s * vkp + c * vkq\n }\n }\n }\n }\n const order = Array.from({ length: n }, (_, index) => index).sort(\n (left, right) => a[right]![right]! - a[left]![left]! || left - right,\n )\n return {\n values: order.map((index) => a[index]![index]!),\n vectors: order.map((index) => orient(v.map((row) => row[index]!))),\n }\n}\n\nfunction orient(vector: number[]): number[] {\n let pivot = 0\n for (let index = 1; index < vector.length; index++) {\n if (Math.abs(vector[index]!) > Math.abs(vector[pivot]!) + 1e-12) pivot = index\n }\n return (vector[pivot] ?? 0) < 0 ? vector.map((value) => (value === 0 ? 0 : -value)) : vector\n}\n","/**\n * The plateau score: how far a search's best improvement over the root rose\n * across its last few measured nodes, in units of noise; and `draftOnPlateau`,\n * the policy that drafts when it is low.\n *\n * It reads only what a `SearchPolicyView` holds, so the `landscape` lens and\n * the policy compute the same number from the same ledger.\n */\n\nimport type { SearchPolicy, SearchPolicyView } from '../../campaign/search-policy'\nimport { round9 } from './geometry'\nimport { INSUFFICIENT_FROM } from './shared'\n\n/** What the plateau reads: a policy view, or the lens's own reading of one. */\nexport type SearchPlateauView = Pick<\n SearchPolicyView,\n 'direction' | 'rootNodeId' | 'screened' | 'complete' | 'unitScores'\n>\n\nexport interface SearchPlateauOptions {\n /** Accepted nodes the rise is measured across. Default 6. */\n window?: number\n}\n\nexport interface SearchPlateau {\n /** `rise / noise`; null when insufficient. Below 1 the best improvement rose\n * less than one standard error across the window: a plateau. */\n value: number | null\n window: number\n /** Screened non-root nodes that dodged no unit and share at least 6 units\n * with the root (the design's `descriptive` threshold), in registration\n * order. Only these can hold the best. */\n accepted: number\n /** The accepted nodes the window covers, oldest first. */\n windowNodes: string[]\n /** Best improvement over the root after the window minus before it; the\n * root itself is the best before any node, at exactly 0. */\n rise: number | null\n /** Standard error of the best node's improvement: sqrt(pooled variance / its\n * shared units). */\n noise: number | null\n best: { nodeId: string; gain: number; pairs: number } | null\n /** Between-unit variance of per-unit improvements over the root, pooled over\n * every screened complete node with 2 or more shared units. */\n pooledVariance: number | null\n degreesOfFreedom: number\n method: string\n insufficient: string | null\n}\n\nexport const PLATEAU_METHOD = `rise of the best improvement over the root across the last \\`window\\` accepted nodes (screened, no dodged unit, ${INSUFFICIENT_FROM} or more units shared with the root), divided by the best node's standard error sqrt(pooled variance / its shared units); an improvement is the mean per-unit gain over the root on shared units in the objective's direction, and the variance is the between-unit variance of those gains pooled over screened nodes with 2 or more shared units`\n\n/**\n * The plateau score of a search. Nodes are taken in the view's screened\n * order, which is registration order. Insufficient with fewer than `window`\n * accepted nodes, or without a pooled variance above zero.\n */\nexport function searchPlateau(\n view: SearchPlateauView,\n options: SearchPlateauOptions = {},\n): SearchPlateau {\n const window = options.window ?? 6\n if (!Number.isSafeInteger(window) || window < 1) {\n throw new TypeError(`searchPlateau: window must be a positive integer, got ${String(window)}`)\n }\n const sign = view.direction === 'maximize' ? 1 : -1\n const root = new Map(view.unitScores(view.rootNodeId).map((unit) => [unit.unitId, unit.mean]))\n const accepted: Array<{ nodeId: string; gain: number; pairs: number }> = []\n let squares = 0\n let degreesOfFreedom = 0\n for (const nodeId of view.screened) {\n if (nodeId === view.rootNodeId || !view.complete(nodeId)) continue\n const deltas: number[] = []\n for (const unit of view.unitScores(nodeId)) {\n const base = root.get(unit.unitId)\n if (base !== undefined) deltas.push(sign * (unit.mean - base))\n }\n if (deltas.length < 2) continue\n let total = 0\n for (const delta of deltas) total += delta\n const mean = total / deltas.length\n for (const delta of deltas) squares += (delta - mean) ** 2\n degreesOfFreedom += deltas.length - 1\n if (deltas.length >= INSUFFICIENT_FROM) {\n accepted.push({ nodeId, gain: mean, pairs: deltas.length })\n }\n }\n const pooledVariance = degreesOfFreedom > 0 ? squares / degreesOfFreedom : null\n const start = Math.max(0, accepted.length - window)\n let before: { nodeId: string; gain: number; pairs: number } | null = null\n for (const entry of accepted.slice(0, start)) {\n if (before === null || entry.gain > before.gain) before = entry\n }\n let best = before\n for (const entry of accepted.slice(start)) {\n if (best === null || entry.gain > best.gain) best = entry\n }\n const base = {\n window,\n accepted: accepted.length,\n windowNodes: accepted.slice(start).map((entry) => entry.nodeId),\n best: best === null ? null : { ...best, gain: round9(best.gain) },\n pooledVariance: pooledVariance === null ? null : round9(pooledVariance),\n degreesOfFreedom,\n method: PLATEAU_METHOD,\n }\n const insufficient = (reason: string): SearchPlateau => ({\n ...base,\n value: null,\n rise: null,\n noise: null,\n insufficient: reason,\n })\n if (accepted.length < window) {\n return insufficient(\n `${accepted.length} of ${window} accepted nodes (screened, no dodged unit, ${INSUFFICIENT_FROM} or more units shared with the root)`,\n )\n }\n if (pooledVariance === null || pooledVariance === 0) {\n return insufficient(\n pooledVariance === null\n ? 'no pooled between-unit variance'\n : 'every per-unit gain equals its node’s mean, so the noise is unmeasured',\n )\n }\n const leader = best!\n const rise = Math.max(0, leader.gain) - Math.max(0, before?.gain ?? 0)\n const noise = Math.sqrt(pooledVariance / leader.pairs)\n return {\n ...base,\n value: round9(rise / noise),\n rise: round9(rise),\n noise: round9(noise),\n insufficient: null,\n }\n}\n\nexport interface DraftOnPlateauOptions {\n /** Accepted nodes the plateau's rise is measured across, and expansions\n * between two drafts. Default 6. */\n window?: number\n /** Draft when the plateau score is below this many standard errors.\n * Default 1: the best improvement rose less than one standard error. */\n below?: number\n}\n\n/**\n * `base`, except that on a plateau it drafts: it proposes a fresh artifact\n * (operator `draft`, anchored on the root) instead of refining one. The\n * plateau is the `landscape` lens's signal (`searchPlateau` on this view):\n * how many standard errors the best improvement over the root rose across the\n * last `window` accepted nodes. A draft needs a measured plateau (at least\n * `window` accepted nodes and a pooled variance) and an expansion count that\n * is a multiple of `window`, so `base` expands at least `window − 1` times\n * between drafts and each draft's lineage gets a chance to lift the plateau.\n * Nodes still screening do not hold a draft back: the kernel expands while\n * its screening backlog is below twice the lane capacity, so under a full\n * pipeline some node is always screening, and the plateau reads only nodes\n * whose screen finished. The leader and patience are `base`'s.\n *\n * This is AIDE's draft trigger driven by measured progress instead of a fixed\n * count; `draftOnPlateau(aide(...))` adds it to `aide`'s own drafts. A draft\n * pays off only when `base` then expands drafts that trail the leader:\n * `incumbent` expands only its leader, so a draft that starts below it is\n * never refined.\n */\nexport function draftOnPlateau(\n base: SearchPolicy,\n options: DraftOnPlateauOptions = {},\n): SearchPolicy {\n const window = options.window ?? 6\n const below = options.below ?? 1\n if (!Number.isSafeInteger(window) || window < 1) {\n throw new TypeError(`draftOnPlateau: window must be a positive integer, got ${String(window)}`)\n }\n if (!(below > 0) || !Number.isFinite(below)) {\n throw new TypeError(`draftOnPlateau: below must be a positive number, got ${String(below)}`)\n }\n const name = `draft-on-plateau(${base.name},window=${window},below=${below})`\n return {\n name,\n ...(base.patience === undefined ? {} : { patience: base.patience }),\n leader: (view) => base.leader(view),\n expand(view) {\n if (view.expansions % window !== 0) return base.expand(view)\n const plateau = searchPlateau(view, { window })\n if (plateau.value === null || plateau.value >= below) return base.expand(view)\n return {\n parents: [view.rootNodeId],\n operator: 'draft',\n selection: {\n rule: name,\n evidence: {\n plateau: plateau.value,\n rise: plateau.rise!,\n noise: plateau.noise!,\n window,\n accepted: plateau.accepted,\n expansions: view.expansions,\n },\n },\n }\n },\n }\n}\n","/**\n * The landscape lens: where each node sits in edit space, and how the score\n * varies over it.\n *\n * Nodes are placed in two dimensions by landmark classical multidimensional\n * scaling (de Silva and Tenenbaum, 2004) of a pluggable distance between\n * their profiles. The default distance counts the edits the ledger recorded\n * between two profiles along their lineage; a caller that can read the\n * surface blobs passes `surfaceTextEdits`, and a caller with a model\n * embedding passes `vectorEmbedding`. Every node's score is its improvement\n * over the root on the units both scored, in the objective's direction, with\n * the standard error its shared units give it. Kriging (Gaussian-process\n * regression with each node's own noise) interpolates the scores over a grid\n * and leaves a cell unknown where the nodes do not constrain it. Basins are\n * the peaks of the node scores on the nearest-neighbour graph that stand\n * above their saddle by more than the noise, Bonferroni-bounded over the\n * graph's local maxima (0-dimensional persistence of the superlevel sets,\n * ToMATo).\n *\n * The signal is `plateau`: how far the best improvement over the root rose\n * across the last `window` screened nodes, in units of that node's standard\n * error. Below 1 the search is on a plateau; a policy that drafts afresh when\n * it is (`draftOnPlateau`) reads the same function on its own view.\n */\n\nimport { searchEstimateMethod, searchPosterior } from '../../campaign/estimate-node'\nimport { searchPolicyView } from '../../campaign/search-kernel'\nimport type {\n SearchCandidateSurface,\n SearchEstimateMethod,\n SearchNodeStatus,\n} from '../../campaign/search-ledger-types'\nimport type { SearchNode, SearchStateView } from '../../campaign/search-state'\nimport { canonicalString, compareCodeUnits } from '../../ledger-core/canonical'\nimport { cholesky } from '../../math/cholesky'\nimport { symmetricEigen } from '../../math/symmetric-eigen'\nimport { zQuantile } from '../../statistics/internal'\nimport {\n evenSample,\n type GeometryLensResult,\n type GeometrySignal,\n headSequence,\n median,\n plural,\n positiveInteger,\n round9,\n screenedNodes,\n} from './geometry'\nimport { PLATEAU_METHOD, type SearchPlateau, searchPlateau } from './plateau'\nimport { INSUFFICIENT_FROM, rankingSplit } from './shared'\n\n// ── Embeddings ───────────────────────────────────────────────────────\n\n/**\n * How the lens measures the distance between two nodes' profiles.\n *\n * - `lineage`: edits along the lineage graph, one per recorded improve,\n * debug or merge edge between nodes of this search. A draft edge is not an\n * edit (the draft is written afresh), so a draft's lineage is unreachable\n * by this distance and unplaced, never guessed; `surfaceTextEdits` places it.\n * - `distance`: any symmetric distance; null when it cannot be measured.\n * - `vector`: a vector per node, for example a model embedding of the\n * profile; nodes are compared by Euclidean distance.\n */\nexport type LandscapeEmbedding =\n | { kind: 'lineage'; name: string; method: string }\n | {\n kind: 'distance'\n name: string\n method: string\n distance(a: SearchNode, b: SearchNode): number | null\n }\n | {\n kind: 'vector'\n name: string\n method: string\n vector(node: SearchNode): readonly number[] | null\n }\n\n/** The default: edits recorded between two profiles along the lineage. */\nexport function lineageEdits(): LandscapeEmbedding {\n return {\n kind: 'lineage',\n name: 'lineage-edits',\n method:\n 'edits between the two profiles along the recorded lineage: the fewest improve, debug or merge edges joining them (a re-proposal edge counts; a draft is written afresh, so its edge is no edit of its anchor)',\n }\n}\n\n/** Surfaces whose content digests differ: the edit distance between two\n * profiles at the granularity of their declared surfaces. */\nexport function surfaceDigestEdits(): LandscapeEmbedding {\n return {\n kind: 'distance',\n name: 'surface-digest-edits',\n method: 'declared surfaces whose content digests differ (a surface only one node has counts)',\n distance(a, b) {\n const left = new Map(\n a.surfaces.map((surface) => [surface.surfaceId, surface.artifact.sha256]),\n )\n let count = 0\n const seen = new Set<string>()\n for (const surface of b.surfaces) {\n seen.add(surface.surfaceId)\n if (left.get(surface.surfaceId) !== surface.artifact.sha256) count += 1\n }\n for (const surfaceId of left.keys()) if (!seen.has(surfaceId)) count += 1\n return count\n },\n }\n}\n\n/**\n * Line edits between the surfaces' texts: for each declared surface, the\n * fewest line insertions and deletions that turn one text into the other\n * (Myers, 1986), summed over surfaces. `read` returns a surface's content:\n * a string, parsed JSON (flattened with `profileTextLines`), or null when it\n * cannot be read, which leaves every distance of that node unknown. The lens\n * stays pure; the caller owns the I/O and its verification.\n */\nexport function surfaceTextEdits(\n read: (surface: SearchCandidateSurface) => unknown,\n): LandscapeEmbedding {\n const lines = new Map<string, string[] | null>()\n const linesOf = (surface: SearchCandidateSurface): string[] | null => {\n const key = surface.artifact.sha256\n if (!lines.has(key)) {\n const content = read(surface)\n lines.set(\n key,\n content === null || content === undefined\n ? null\n : typeof content === 'string'\n ? content.split('\\n')\n : profileTextLines(content),\n )\n }\n return lines.get(key)!\n }\n return {\n kind: 'distance',\n name: 'surface-text-edits',\n method:\n 'line insertions plus deletions between the surface texts (Myers diff), summed over declared surfaces; JSON is flattened to one line per leaf and per line of a string',\n distance(a, b) {\n const right = new Map(b.surfaces.map((surface) => [surface.surfaceId, surface]))\n let total = 0\n const seen = new Set<string>()\n for (const surface of a.surfaces) {\n seen.add(surface.surfaceId)\n const own = linesOf(surface)\n if (own === null) return null\n const other = right.get(surface.surfaceId)\n if (!other) {\n total += own.length\n continue\n }\n if (other.artifact.sha256 === surface.artifact.sha256) continue\n const theirs = linesOf(other)\n if (theirs === null) return null\n total += lineEditDistance(own, theirs)\n }\n for (const surface of b.surfaces) {\n if (seen.has(surface.surfaceId)) continue\n const theirs = linesOf(surface)\n if (theirs === null) return null\n total += theirs.length\n }\n return total\n },\n }\n}\n\n/** A caller's vector per node, for example a model embedding of its profile. */\nexport function vectorEmbedding(\n name: string,\n vector: (node: SearchNode) => readonly number[] | null,\n): LandscapeEmbedding {\n return {\n kind: 'vector',\n name,\n method: `Euclidean distance between ${name} vectors`,\n vector,\n }\n}\n\n/**\n * JSON as lines a diff can count: one line per scalar leaf, `path=value`, and\n * one line per line of a string, so an edit inside a long prompt counts the\n * lines it changed rather than the whole prompt. Object keys are visited in\n * code-unit order.\n */\nexport function profileTextLines(value: unknown, path = '$'): string[] {\n if (typeof value === 'string') {\n const parts = value.split('\\n')\n return parts.length === 1\n ? [`${path}=${canonicalString(value)}`]\n : parts.map((line, index) => `${path}[${index}]=${canonicalString(line)}`)\n }\n if (Array.isArray(value)) {\n if (value.length === 0) return [`${path}=[]`]\n return value.flatMap((entry, index) => profileTextLines(entry, `${path}[${index}]`))\n }\n if (value !== null && typeof value === 'object') {\n const keys = Object.keys(value).sort(compareCodeUnits)\n if (keys.length === 0) return [`${path}={}`]\n return keys.flatMap((key) =>\n profileTextLines((value as Record<string, unknown>)[key], `${path}.${key}`),\n )\n }\n return [`${path}=${canonicalString(value ?? null)}`]\n}\n\n/** Fewest line insertions plus deletions turning `a` into `b` (Myers' O(ND)\n * greedy algorithm, which is fast when the texts are close). */\nexport function lineEditDistance(a: readonly string[], b: readonly string[]): number {\n const n = a.length\n const m = b.length\n const max = n + m\n if (max === 0) return 0\n const offset = max\n const v = new Int32Array(2 * max + 2)\n for (let d = 0; d <= max; d++) {\n for (let k = -d; k <= d; k += 2) {\n let x =\n k === -d || (k !== d && v[offset + k - 1]! < v[offset + k + 1]!)\n ? v[offset + k + 1]!\n : v[offset + k - 1]! + 1\n let y = x - k\n while (x < n && y < m && a[x] === b[y]) {\n x += 1\n y += 1\n }\n v[offset + k] = x\n if (x >= n && y >= m) return d\n }\n }\n return max\n}\n\n// ── The lens ─────────────────────────────────────────────────────────\n\nexport interface LandscapeOptions {\n /** The split scores come from. Default: the ranked split. */\n split?: 'selection' | 'train'\n /** Landmarks of the scaling. Default 32; a search with fewer nodes scales exactly. */\n landmarks?: number\n /** Grid columns and rows. Default 24. */\n grid?: number\n /** Scored nodes the surface is fitted on, evenly spaced in registration\n * order with the root and the best node always in. Default 400. */\n surfaceNodes?: number\n /** Screened nodes the plateau reads. Default 6. */\n window?: number\n /** Attempts the kernel gives an errored cell. Default 3. */\n maxAttempts?: number\n}\n\nexport interface LandscapeNode {\n nodeId: string\n ordinal: number\n depth: number | null\n status: SearchNodeStatus | null\n /** The operator of the node's first edge. */\n operator: string | null\n /** Null when the node could not be placed; `unplaced` says why. */\n x: number | null\n y: number | null\n unplaced: string | null\n /** Improvement over the root on shared units, larger is better; null\n * without a shared unit. */\n score: number | null\n /** Standard error of `score`: sqrt(pooled variance / pairs); 0 for the\n * root, null when the pooled variance is unknown. */\n standardError: number | null\n pairs: number\n method: SearchEstimateMethod\n /** Index into `basins.peaks`; null when unplaced, unscored, or when basins\n * are insufficient. */\n basin: number | null\n}\n\nexport interface LandscapeGrid {\n columns: number\n rows: number\n x: [number, number]\n y: [number, number]\n /** Posterior mean of the improvement over the root, `values[row][column]`;\n * row 0 is the lowest y. Null where the nodes explain less than half the\n * prior variance: the surface there is unknown, not flat. */\n values: (number | null)[][]\n /** Posterior standard deviation at each cell, supported or not. */\n sd: number[][]\n supportedCells: number\n /** The kriging model: a constant mean, a squared-exponential covariance of\n * `priorVariance` and `lengthScale` (in coordinate units), and each node's\n * own noise variance, pooled variance over its shared units. */\n model: {\n mean: number\n priorVariance: number\n lengthScale: number\n /** Log marginal likelihood of the chosen length scale. */\n logLikelihood: number\n /** Log marginal likelihood of the same scores with no spatial\n * correlation; the surface is drawn only when `logLikelihood` beats it\n * by 1 or more. */\n independentLogLikelihood: number\n /** Nodes the surface was fitted on (at most `surfaceNodes`). */\n fitNodes: number\n }\n method: string\n}\n\nexport interface LandscapeBasin {\n /** The basin's best node: the peak of its component. */\n peak: { nodeId: string; x: number; y: number; score: number; pairs: number }\n /** How far the peak stands above the saddle node where its component first\n * met a higher one; null for the highest peak and for a component that\n * never met a higher one (a separate region of the graph). */\n persistence: number | null\n /** The persistence this peak needed: `z` standard errors of the difference\n * between the peak's and the saddle's scores. Null for the highest peak. */\n threshold: number | null\n saddle: string | null\n nodes: number\n}\n\nexport interface LandscapeData {\n split: 'selection' | 'train'\n direction: 'maximize' | 'minimize'\n embedding: {\n name: string\n method: string\n landmarks: number\n /** Median and largest distance between two landmarks, in the embedding's\n * own unit (for example lines edited): how far apart the profiles are. */\n landmarkDistance: { median: number; max: number } | null\n /** Of the scaled landmark matrix, largest first. */\n eigenvalues: number[]\n /** Share of the positive eigenvalue mass the two axes hold. */\n explained: number | null\n /** Share of the absolute eigenvalue mass that is negative: how far the\n * distance departs from a Euclidean one. */\n negativeMass: number | null\n placed: number\n unplaced: number\n }\n nodes: LandscapeNode[]\n /** Parent-to-child segments of every node's lineage. */\n lineage: Array<{ parent: string; child: string; operator: string }>\n grid: LandscapeGrid | null\n gridInsufficient: string | null\n basins: {\n count: number | null\n /** Neighbours each node joins in the graph the basins are read on. */\n neighbours: number\n /** Nodes with no higher neighbour: the peaks that could each survive. */\n localMaxima: number\n /** Standard errors a peak must clear its saddle by: the Bonferroni\n * normal quantile over `localMaxima − 1` tests at 5%. */\n z: number | null\n /** Nodes the graph holds (at most 2000 plus the 100 best). */\n graphNodes: number\n /** MDS axes the graph's distances use, and their share of the positive\n * eigenvalue mass: the neighbours are near in this space. */\n graphAxes: number\n graphExplained: number | null\n method: string\n insufficient: string | null\n peaks: LandscapeBasin[]\n }\n plateau: SearchPlateau\n}\n\nconst GRID_METHOD =\n \"Gaussian-process regression (ordinary kriging) of node scores: a constant mean (generalized least squares), a squared-exponential covariance whose prior variance is the between-node variance of the scores minus their mean noise and whose length scale maximizes the marginal likelihood over 0.5, 1, 2 and 4 times the median nearest-neighbour distance, and each node's own noise variance (the pooled between-unit variance over its units shared with the root; the root is the reference at exactly 0); nodes with fewer than 2 shared units, and nodes decided invalid, are left out; a cell is null where the posterior variance exceeds half the prior variance, so the surface never extends past the nodes that support it; no surface is drawn unless the length scale raises the log-likelihood by 1 or more over independent node scores\"\n/** Scored nodes a surface or a basin count needs: the library's minimum\n * sample for anything descriptive, as for units. */\nconst SURFACE_MIN_NODES = INSUFFICIENT_FROM\nconst BASIN_METHOD =\n '0-dimensional persistence of node scores on the symmetric k-nearest-neighbour graph of placed nodes (not decided invalid, 2 or more units shared with the root), read on the leading MDS axes that hold 80% of the positive eigenvalue mass (2 to 8), joined into one component by the shortest edge between components (ToMATo, Chazal et al. 2013): nodes enter from the highest score down, and where two components meet, the lower peak merges into the higher unless it stands above that saddle node by z standard errors of their difference, sqrt(pooled variance / shared units) per node, where z is the standard-normal quantile at 1 − 0.05 / (local maxima − 1), a Bonferroni bound over every peak that could survive, so a flat landscape of noisy nodes counts one basin at least 95% of the time; at most 2000 nodes, evenly spaced by registration plus the 100 best'\n/** Nodes the basin graph holds: evenly spaced by registration, plus the best. */\nconst BASIN_NODES = 2000\nconst BASIN_TOP = 100\n\n/**\n * The landscape of a search: every node placed by `embed`, the interpolated\n * score over the placement, the basins of that surface, and the plateau\n * signal. Pure: it reads the state and calls `embed`.\n */\nexport function landscape(\n state: SearchStateView,\n embed: LandscapeEmbedding = lineageEdits(),\n options: LandscapeOptions = {},\n): GeometryLensResult<LandscapeData> {\n const landmarkCap = positiveInteger('landscape', 'landmarks', options.landmarks ?? 32)\n const columns = positiveInteger('landscape', 'grid', options.grid ?? 24)\n const surfaceNodes = positiveInteger('landscape', 'surfaceNodes', options.surfaceNodes ?? 400)\n const window = options.window ?? 6\n const header = state.header\n const split = options.split ?? rankingSplit(state)\n const direction = header?.objective.direction ?? 'maximize'\n const plateauEmpty = (reason: string): SearchPlateau => ({\n value: null,\n window,\n accepted: 0,\n windowNodes: [],\n rise: null,\n noise: null,\n best: null,\n pooledVariance: null,\n degreesOfFreedom: 0,\n method: PLATEAU_METHOD,\n insufficient: reason,\n })\n const rootNodeId = header ? state.rootNodeId : null\n if (!header || rootNodeId === null) {\n const reason = header ? 'the search has no root node yet' : 'the search has not been opened'\n return result(state, emptyData(split, direction, embed, reason, plateauEmpty(reason)))\n }\n\n const nodes = state.nodes()\n const index = new Map(nodes.map((node, position) => [node.nodeId, position]))\n const posterior = searchPosterior(state, { split })\n const scoreOf = new Map(posterior.nodes.map((entry) => [entry.nodeId, entry]))\n const placement = placeNodes(nodes, index, rootNodeId, embed, landmarkCap, () =>\n lineageAdjacency(state, index),\n )\n\n const records: LandscapeNode[] = nodes.map((node, position) => {\n const entry = scoreOf.get(node.nodeId)!\n const firstEdge = node.edgeIds[0] ? state.edge(node.edgeIds[0]) : undefined\n const at = placement.coordinates[position]\n return {\n nodeId: node.nodeId,\n ordinal: node.ordinal,\n depth: node.depth,\n status: node.status,\n operator: firstEdge?.operator ?? null,\n x: at ? round9(at[0]) : null,\n y: at ? round9(at[1]) : null,\n unplaced: at ? null : (placement.unplaced.get(position) ?? 'not placed'),\n // One shared unit is no estimate (§6.4: unknown below 2 units); the\n // root is the reference, exactly 0.\n score:\n entry.mean === null || (entry.pairs < 2 && node.nodeId !== rootNodeId)\n ? null\n : round9(entry.mean),\n standardError: entry.variance === null ? null : round9(Math.sqrt(entry.variance)),\n pairs: entry.pairs,\n method: searchEstimateMethod(entry.pairs),\n basin: null,\n }\n })\n const lineage: LandscapeData['lineage'] = []\n for (const node of nodes) {\n const operator = node.edgeIds[0] ? (state.edge(node.edgeIds[0])?.operator ?? 'unknown') : 'none'\n for (const parent of node.parents) {\n if (parent.searchId !== state.searchId) continue\n lineage.push({ parent: parent.nodeId, child: node.nodeId, operator })\n }\n }\n\n // A node decided invalid keeps its place and score on the map, but its\n // score (a judge integrity or admission failure, possibly a reward hack)\n // shapes neither the surface nor a basin.\n const scored = records.filter(\n (record) =>\n record.x !== null &&\n record.score !== null &&\n record.pairs >= 2 &&\n record.status !== 'invalid',\n )\n const variances = new Map(posterior.nodes.map((entry) => [entry.nodeId, entry.variance]))\n const gridResult = krige(records, scored, variances, columns, surfaceNodes)\n const fullOf = new Map<string, number[]>()\n nodes.forEach((node, position) => {\n const point = placement.full[position]\n if (point) fullOf.set(node.nodeId, point)\n })\n const basins = graphBasins(\n records,\n scored,\n fullOf,\n { axes: placement.fullAxes, explained: placement.fullExplained },\n posterior.pooledVariance,\n posterior.degreesOfFreedom,\n )\n\n const view = searchPolicyView(state, {\n screened: screenedNodes(state, { maxAttempts: options.maxAttempts }),\n screening: 0,\n expansions: 0,\n ...(options.maxAttempts === undefined ? {} : { maxAttempts: options.maxAttempts }),\n })\n // The plateau reads the policy's own view, so a policy that drafts on it\n // (`draftOnPlateau`) sees this number; it ranks on the policy's split.\n const plateau = searchPlateau(view, { window })\n\n return result(state, {\n split,\n direction,\n embedding: {\n name: embed.name,\n method: embed.method,\n landmarks: placement.landmarks,\n landmarkDistance: placement.landmarkDistance,\n eigenvalues: placement.eigenvalues.map(round9),\n explained: placement.explained === null ? null : round9(placement.explained),\n negativeMass: placement.negativeMass === null ? null : round9(placement.negativeMass),\n placed: records.filter((record) => record.x !== null).length,\n unplaced: records.filter((record) => record.x === null).length,\n },\n nodes: records,\n lineage,\n grid: gridResult.grid,\n gridInsufficient: gridResult.insufficient,\n basins,\n plateau,\n })\n}\n\nfunction result(state: SearchStateView, data: LandscapeData): GeometryLensResult<LandscapeData> {\n const { plateau } = data\n const signal: GeometrySignal = {\n name: 'plateau',\n value: plateau.value,\n subject: plateau.best?.nodeId ?? null,\n method: plateau.method,\n n: plateau.accepted,\n insufficient: plateau.insufficient,\n }\n return {\n lens: 'landscape',\n searchId: state.searchId,\n sequence: headSequence(state),\n data,\n signal,\n }\n}\n\nfunction emptyData(\n split: 'selection' | 'train',\n direction: 'maximize' | 'minimize',\n embed: LandscapeEmbedding,\n reason: string,\n plateau: SearchPlateau,\n): LandscapeData {\n return {\n split,\n direction,\n embedding: {\n name: embed.name,\n method: embed.method,\n landmarks: 0,\n landmarkDistance: null,\n eigenvalues: [],\n explained: null,\n negativeMass: null,\n placed: 0,\n unplaced: 0,\n },\n nodes: [],\n lineage: [],\n grid: null,\n gridInsufficient: reason,\n basins: {\n count: null,\n neighbours: 0,\n localMaxima: 0,\n z: null,\n graphNodes: 0,\n graphAxes: 0,\n graphExplained: null,\n method: BASIN_METHOD,\n insufficient: reason,\n peaks: [],\n },\n plateau,\n }\n}\n\n// ── Placement: landmark classical MDS ────────────────────────────────\n\ninterface Placement {\n coordinates: Array<[number, number] | undefined>\n /** Coordinates on the leading axes that hold 80% of the positive\n * eigenvalue mass (2 to 8 axes): the space the basin graph is read in, so\n * neighbours are near in the distance itself, not only in the 2-D map. */\n full: Array<number[] | undefined>\n /** Axes `full` holds, and their share of the positive eigenvalue mass. */\n fullAxes: number\n fullExplained: number | null\n unplaced: Map<number, string>\n landmarks: number\n landmarkDistance: { median: number; max: number } | null\n eigenvalues: number[]\n explained: number | null\n negativeMass: number | null\n}\n\nfunction placeNodes(\n nodes: readonly SearchNode[],\n index: ReadonlyMap<string, number>,\n rootNodeId: string,\n embed: LandscapeEmbedding,\n landmarkCap: number,\n adjacency: () => number[][],\n): Placement {\n const n = nodes.length\n const distancesFrom = distanceRows(nodes, embed, adjacency)\n const unplaced = new Map<number, string>()\n const coordinates: Placement['coordinates'] = new Array(n).fill(undefined)\n const first = index.get(rootNodeId) ?? 0\n const rows: Array<Array<number | null>> = []\n const chosen: number[] = []\n const nearest = new Array<number>(n).fill(Number.POSITIVE_INFINITY)\n let pick: number | null = first\n while (pick !== null && chosen.length < landmarkCap) {\n const row = distancesFrom(pick)\n rows.push(row)\n chosen.push(pick)\n for (let j = 0; j < n; j++) {\n const d = row[j]\n if (unplaced.has(j)) continue\n if (d === null || d === undefined || !Number.isFinite(d) || d < 0) {\n unplaced.set(\n j,\n chosen.length === 1\n ? `no ${embed.name} distance to the root`\n : `no ${embed.name} distance to landmark ${nodes[pick]!.nodeId}`,\n )\n continue\n }\n nearest[j] = Math.min(nearest[j]!, d)\n }\n if (unplaced.has(first)) break\n let next: number | null = null\n for (let j = 0; j < n; j++) {\n if (unplaced.has(j) || chosen.includes(j) || nearest[j]! <= 0) continue\n if (next === null || nearest[j]! > nearest[next]!) next = j\n }\n pick = next\n }\n // A landmark that later lost its own placement cannot anchor the scaling.\n const usable = chosen.map((node, position) => ({ node, row: rows[position]! }))\n const landmarks = usable.filter(({ node }) => !unplaced.has(node))\n if (landmarks.length === 0) {\n for (let j = 0; j < n; j++) {\n if (!unplaced.has(j)) unplaced.set(j, `the root has no ${embed.name} placement`)\n }\n return {\n coordinates,\n full: new Array(n).fill(undefined),\n fullAxes: 0,\n fullExplained: null,\n unplaced,\n landmarks: 0,\n landmarkDistance: null,\n eigenvalues: [],\n explained: null,\n negativeMass: null,\n }\n }\n const L = landmarks.length\n const squared = landmarks.map(({ row: rowA, node: a }) =>\n landmarks.map(({ row: rowB, node: b }) => {\n const d = ((rowA[b] ?? 0) + (rowB[a] ?? 0)) / 2\n return d * d\n }),\n )\n const columnMean = squared[0]!.map((_, j) => squared.reduce((sum, row) => sum + row[j]!, 0) / L)\n const grand = columnMean.reduce((sum, value) => sum + value, 0) / L\n const b = squared.map((row, i) =>\n row.map((value, j) => -0.5 * (value - columnMean[i]! - columnMean[j]! + grand)),\n )\n const between: number[] = []\n for (let i = 0; i < L; i++)\n for (let j = i + 1; j < L; j++) between.push(Math.sqrt(squared[i]![j]!))\n const { values, vectors } = symmetricEigen(b)\n const positive = values.filter((value) => value > 1e-12)\n const positiveMass = positive.reduce((sum, value) => sum + value, 0)\n const negativeMass = values\n .filter((value) => value < -1e-12)\n .reduce((sum, value) => sum - value, 0)\n let fullAxes = 2\n let held = values.slice(0, 2).reduce((sum, value) => sum + Math.max(value, 0), 0)\n while (\n fullAxes < FULL_AXES_MAX &&\n positiveMass > 0 &&\n held / positiveMass < FULL_AXES_MASS &&\n (values[fullAxes] ?? 0) > 1e-12\n ) {\n held += values[fullAxes]!\n fullAxes += 1\n }\n const allAxes = Array.from({ length: fullAxes }, (_, k) =>\n (values[k] ?? 0) > 1e-12 ? { value: values[k]!, vector: vectors[k]! } : null,\n )\n const axes = allAxes.slice(0, 2)\n const full: Placement['full'] = new Array(n).fill(undefined)\n for (let j = 0; j < n; j++) {\n if (unplaced.has(j)) continue\n const coordinate = allAxes.map((axis) => {\n if (axis === null) return 0\n let sum = 0\n for (let l = 0; l < L; l++) {\n const d = landmarks[l]!.row[j]!\n sum += (d * d - columnMean[l]!) * axis.vector[l]!\n }\n return (-0.5 * sum) / Math.sqrt(axis.value)\n })\n coordinates[j] = [coordinate[0]!, coordinate[1]!]\n full[j] = coordinate\n }\n return {\n coordinates,\n full,\n fullAxes,\n fullExplained: positiveMass > 0 ? Math.min(1, held / positiveMass) : null,\n unplaced,\n landmarks: L,\n landmarkDistance:\n between.length === 0\n ? null\n : { median: round9(median(between)!), max: round9(Math.max(...between)) },\n eigenvalues: values,\n explained:\n positiveMass > 0\n ? axes.reduce((sum, axis) => sum + (axis?.value ?? 0), 0) / positiveMass\n : null,\n negativeMass:\n positiveMass + negativeMass > 0 ? negativeMass / (positiveMass + negativeMass) : null,\n }\n}\n\n/**\n * The undirected lineage graph by node index: an edge joins a child to each\n * parent in this search when its operator edits a parent (improve, debug,\n * merge). Every recorded edge counts, re-proposals into an existing node\n * included, since each says the child is one edit from that parent.\n */\nfunction lineageAdjacency(state: SearchStateView, index: ReadonlyMap<string, number>): number[][] {\n const neighbours: Set<number>[] = Array.from({ length: index.size }, () => new Set<number>())\n for (const edge of state.edges()) {\n if (edge.operator !== 'improve' && edge.operator !== 'debug' && edge.operator !== 'merge') {\n continue\n }\n const child = index.get(edge.childNodeId)\n if (child === undefined) continue\n for (const parent of edge.parents) {\n if (parent.searchId !== state.searchId) continue\n const at = index.get(parent.nodeId)\n if (at === undefined || at === child) continue\n neighbours[child]!.add(at)\n neighbours[at]!.add(child)\n }\n }\n return neighbours.map((set) => [...set].sort((left, right) => left - right))\n}\n\n/** Distances from one node to every node, by the embedding's kind. */\nfunction distanceRows(\n nodes: readonly SearchNode[],\n embed: LandscapeEmbedding,\n adjacency: () => number[][],\n): (from: number) => Array<number | null> {\n const n = nodes.length\n if (embed.kind === 'lineage') {\n const neighbours = adjacency()\n return (from) => {\n const hops: Array<number | null> = new Array(n).fill(null)\n hops[from] = 0\n const queue = [from]\n for (let head = 0; head < queue.length; head++) {\n const at = queue[head]!\n for (const next of neighbours[at]!) {\n if (hops[next] !== null) continue\n hops[next] = hops[at]! + 1\n queue.push(next)\n }\n }\n return hops\n }\n }\n if (embed.kind === 'vector') {\n const vectors = nodes.map((node) => embed.vector(node))\n const size = vectors.find((vector) => vector !== null)?.length ?? 0\n return (from) =>\n vectors.map((vector) => {\n const own = vectors[from]\n if (!own || !vector || own.length !== size || vector.length !== size) return null\n let sum = 0\n for (let d = 0; d < size; d++) sum += (own[d]! - vector[d]!) ** 2\n return Math.sqrt(sum)\n })\n }\n return (from) => nodes.map((node, j) => (j === from ? 0 : embed.distance(nodes[from]!, node)))\n}\n\n// ── Interpolation and basins ─────────────────────────────────────────\n\n/**\n * The score surface by ordinary kriging. Each scored node is a noisy\n * observation of the surface at its placement, with its own noise variance\n * (the root, the reference, is exact). The prior variance is the scores'\n * between-node variance minus their mean noise; when that is not positive the\n * nodes do not differ beyond noise and there is no surface to draw. The length\n * scale maximizes the marginal likelihood over a few multiples of the median\n * nearest-neighbour distance, never below one grid cell.\n */\nfunction krige(\n records: readonly LandscapeNode[],\n scored: readonly LandscapeNode[],\n variances: ReadonlyMap<string, number | null>,\n columns: number,\n surfaceNodes: number,\n): { grid: LandscapeGrid | null; insufficient: string | null } {\n if (scored.length < SURFACE_MIN_NODES) {\n return {\n grid: null,\n insufficient: `${plural(scored.length, 'placed node')} not decided invalid share 2 or more units with the root; a surface needs ${SURFACE_MIN_NODES}`,\n }\n }\n const noiseOf = (node: LandscapeNode): number | null => variances.get(node.nodeId) ?? null\n if (scored.some((node) => noiseOf(node) === null)) {\n return {\n grid: null,\n insufficient: 'no pooled between-unit variance, so the noise of a node’s score is unknown',\n }\n }\n let [x0, x1, y0, y1] = [\n Number.POSITIVE_INFINITY,\n Number.NEGATIVE_INFINITY,\n Number.POSITIVE_INFINITY,\n Number.NEGATIVE_INFINITY,\n ]\n for (const record of records) {\n if (record.x === null || record.y === null) continue\n x0 = Math.min(x0, record.x)\n x1 = Math.max(x1, record.x)\n y0 = Math.min(y0, record.y)\n y1 = Math.max(y1, record.y)\n }\n const span = Math.max(x1 - x0, y1 - y0)\n if (span <= 0) {\n return { grid: null, insufficient: 'every placed node sits at one point' }\n }\n const pad = span * 0.05\n x0 -= pad\n x1 += pad\n y0 -= pad\n y1 += pad\n // Fit on at most `surfaceNodes`, evenly spaced by registration, with the\n // root (the reference) and the best node always in.\n const byScore = [...scored].sort(\n (left, right) => right.score! - left.score! || left.ordinal - right.ordinal,\n )\n const keep = new Set(evenSample(scored, surfaceNodes))\n const rootNode = scored.find((node) => noiseOf(node) === 0)\n for (const must of [rootNode, byScore[0]]) {\n if (!must || keep.has(must)) continue\n const drop = [...keep].reverse().find((node) => node !== rootNode && node !== byScore[0])\n if (drop) keep.delete(drop)\n keep.add(must)\n }\n const fit = scored.filter((node) => keep.has(node))\n const n = fit.length\n const y = fit.map((node) => node.score!)\n const noise = fit.map((node) => noiseOf(node)!)\n const meanScore = y.reduce((sum, value) => sum + value, 0) / n\n const spread = y.reduce((sum, value) => sum + (value - meanScore) ** 2, 0) / (n - 1)\n const meanNoise = noise.reduce((sum, value) => sum + value, 0) / n\n const priorVariance = spread - meanNoise\n if (!(priorVariance > 0)) {\n return {\n grid: null,\n insufficient: `the nodes' scores vary no more than their noise (between-node variance ${fixed(spread)}, mean noise variance ${fixed(meanNoise)}), so there is no surface beyond a flat one`,\n }\n }\n const cell = Math.max(x1 - x0, y1 - y0) / columns\n const nearest = evenSample(fit, 2000).map((a, _, sample) => {\n let best = Number.POSITIVE_INFINITY\n for (const b of sample) {\n if (a === b) continue\n const d = Math.hypot(a.x! - b.x!, a.y! - b.y!)\n if (d > 0 && d < best) best = d\n }\n return best\n })\n const typical = Math.max(median(nearest.filter(Number.isFinite)) ?? cell, cell)\n // Distances are squared once; each length scale reuses them.\n const d2 = fit.map((a) => fit.map((b) => (a.x! - b.x!) ** 2 + (a.y! - b.y!) ** 2))\n const jitter = priorVariance * 1e-9\n let best: {\n lengthScale: number\n lower: number[][]\n alpha: number[]\n mean: number\n logLikelihood: number\n } | null = null\n for (const multiple of [0.5, 1, 2, 4]) {\n const lengthScale = Math.max(typical * multiple, cell)\n const covariance = d2.map((row, i) =>\n row.map(\n (value, j) =>\n priorVariance * Math.exp(-value / (2 * lengthScale * lengthScale)) +\n (i === j ? noise[i]! + jitter : 0),\n ),\n )\n const lower = cholesky(covariance)\n if (lower === null) continue\n // Generalized least squares for the constant mean: 1ᵀC⁻¹y / 1ᵀC⁻¹1.\n const ones = forward(lower, new Array<number>(n).fill(1))\n const whiteY = forward(lower, y)\n let numerator = 0\n let denominator = 0\n for (let i = 0; i < n; i++) {\n numerator += ones[i]! * whiteY[i]!\n denominator += ones[i]! * ones[i]!\n }\n const mean = numerator / denominator\n const residual = forward(\n lower,\n y.map((value) => value - mean),\n )\n let quadratic = 0\n let logDeterminant = 0\n for (let i = 0; i < n; i++) {\n quadratic += residual[i]! ** 2\n logDeterminant += 2 * Math.log(lower[i]![i]!)\n }\n const logLikelihood = -0.5 * (quadratic + logDeterminant + n * Math.log(2 * Math.PI))\n if (best === null || logLikelihood > best.logLikelihood) {\n best = { lengthScale, lower, alpha: backward(lower, residual), mean, logLikelihood }\n }\n }\n if (best === null) {\n return { grid: null, insufficient: 'the kriging covariance is not positive definite' }\n }\n // The same scores with no spatial correlation: each node its own draw of\n // the prior around the mean. A surface is worth drawing only when distance\n // predicts score better than this, by more than the length scale's one\n // extra parameter costs (Akaike: 1 log-likelihood unit).\n const independent = independentLogLikelihood(y, noise, priorVariance)\n if (best.logLikelihood - independent < 1) {\n return {\n grid: null,\n insufficient: `node scores do not correlate with distance in this embedding (log-likelihood ${fixed(best.logLikelihood)} with a length scale against ${fixed(independent)} without one), so a surface would only interpolate noise`,\n }\n }\n const { lengthScale, lower, alpha, mean } = best\n const rows = columns\n const values: (number | null)[][] = []\n const sd: number[][] = []\n let supported = 0\n for (let r = 0; r < rows; r++) {\n const row: (number | null)[] = []\n const sdRow: number[] = []\n const gy = y0 + ((r + 0.5) * (y1 - y0)) / rows\n for (let c = 0; c < columns; c++) {\n const gx = x0 + ((c + 0.5) * (x1 - x0)) / columns\n const k = fit.map(\n (node) =>\n priorVariance *\n Math.exp(-((node.x! - gx) ** 2 + (node.y! - gy) ** 2) / (2 * lengthScale * lengthScale)),\n )\n let value = mean\n for (let i = 0; i < n; i++) value += k[i]! * alpha[i]!\n const white = forward(lower, k)\n let explained = 0\n for (const entry of white) explained += entry * entry\n const variance = Math.max(0, priorVariance - explained)\n sdRow.push(round9(Math.sqrt(variance)))\n if (variance <= priorVariance / 2) {\n row.push(round9(value))\n supported += 1\n } else {\n row.push(null)\n }\n }\n values.push(row)\n sd.push(sdRow)\n }\n return {\n grid: {\n columns,\n rows,\n x: [round9(x0), round9(x1)],\n y: [round9(y0), round9(y1)],\n values,\n sd,\n supportedCells: supported,\n model: {\n mean: round9(mean),\n priorVariance: round9(priorVariance),\n lengthScale: round9(lengthScale),\n logLikelihood: round9(best.logLikelihood),\n independentLogLikelihood: round9(independent),\n fitNodes: n,\n },\n method: GRID_METHOD,\n },\n insufficient: null,\n }\n}\n\n/** Log likelihood of scores drawn independently around a generalized\n * least-squares mean, each with the prior variance plus its own noise. */\nfunction independentLogLikelihood(\n y: readonly number[],\n noise: readonly number[],\n priorVariance: number,\n): number {\n let numerator = 0\n let denominator = 0\n for (let i = 0; i < y.length; i++) {\n const variance = priorVariance + noise[i]!\n numerator += y[i]! / variance\n denominator += 1 / variance\n }\n const mean = numerator / denominator\n let total = 0\n for (let i = 0; i < y.length; i++) {\n const variance = priorVariance + noise[i]!\n total += -0.5 * ((y[i]! - mean) ** 2 / variance + Math.log(2 * Math.PI * variance))\n }\n return total\n}\n\n/** Solves L z = b for lower-triangular L. */\nfunction forward(lower: readonly (readonly number[])[], b: readonly number[]): number[] {\n const n = lower.length\n const z = new Array<number>(n).fill(0)\n for (let i = 0; i < n; i++) {\n const row = lower[i]!\n let value = b[i]!\n for (let k = 0; k < i; k++) value -= row[k]! * z[k]!\n z[i] = value / row[i]!\n }\n return z\n}\n\n/** Solves Lᵀ x = z for lower-triangular L. */\nfunction backward(lower: readonly (readonly number[])[], z: readonly number[]): number[] {\n const n = lower.length\n const x = new Array<number>(n).fill(0)\n for (let i = n - 1; i >= 0; i--) {\n let value = z[i]!\n for (let k = i + 1; k < n; k++) value -= lower[k]![i]! * x[k]!\n x[i] = value / lower[i]![i]!\n }\n return x\n}\n\nfunction cellOf(grid: LandscapeGrid, x: number, y: number): number | null {\n const c = Math.min(\n grid.columns - 1,\n Math.max(0, Math.floor(((x - grid.x[0]) / (grid.x[1] - grid.x[0])) * grid.columns)),\n )\n const r = Math.min(\n grid.rows - 1,\n Math.max(0, Math.floor(((y - grid.y[0]) / (grid.y[1] - grid.y[0])) * grid.rows)),\n )\n return grid.values[r]![c] === null ? null : r * grid.columns + c\n}\n\n/**\n * Basins on the k-nearest-neighbour graph of the scored, placed nodes, by\n * ToMATo's sweep. Nodes enter from the highest score down (earlier\n * registration first on a tie). A node with no entered neighbour starts a\n * component, of which it is the peak; otherwise it joins its highest entered\n * neighbour's component. Where it touches another component, the one with\n * the lower peak merges into the higher unless its peak stands above this\n * node, the saddle, by two standard errors of their difference; a component\n * that survives its first saddle keeps that persistence. Every component left\n * at the end is a basin, labelled by its peak.\n */\nfunction graphBasins(\n records: readonly LandscapeNode[],\n scoredNodes: readonly LandscapeNode[],\n fullOf: ReadonlyMap<string, readonly number[]>,\n space: { axes: number; explained: number | null },\n pooledVariance: number | null,\n degreesOfFreedom: number,\n): LandscapeData['basins'] {\n const empty = (reason: string): LandscapeData['basins'] => ({\n count: null,\n neighbours: 0,\n localMaxima: 0,\n z: null,\n graphNodes: 0,\n graphAxes: 0,\n graphExplained: null,\n method: BASIN_METHOD,\n insufficient: reason,\n peaks: [],\n })\n let scored = scoredNodes\n if (scored.length < SURFACE_MIN_NODES) {\n return empty(\n `${plural(scored.length, 'placed node')} not decided invalid share 2 or more units with the root; basins need ${SURFACE_MIN_NODES}`,\n )\n }\n if (pooledVariance === null || pooledVariance <= 0) {\n return empty('no pooled between-unit variance, so the noise a peak must clear is unknown')\n }\n const sample = new Set(evenSample(scored, BASIN_NODES))\n for (const node of [...scored]\n .sort((left, right) => right.score! - left.score! || left.ordinal - right.ordinal)\n .slice(0, BASIN_TOP)) {\n sample.add(node)\n }\n scored = scoredNodes.filter((node) => sample.has(node))\n const k = Math.min(BASIN_NEIGHBOURS, scored.length - 1)\n const points = scored.map((node) => fullOf.get(node.nodeId) ?? [node.x!, node.y!])\n const adjacency = connectComponents(points, nearestNeighbours(points, k))\n const variance = (index: number) => pooledVariance / scored[index]!.pairs\n const order = scored\n .map((_, index) => index)\n .sort(\n (left, right) =>\n scored[right]!.score! - scored[left]!.score! ||\n scored[left]!.ordinal - scored[right]!.ordinal,\n )\n const rank = new Int32Array(scored.length)\n order.forEach((index, position) => {\n rank[index] = position\n })\n const parent = new Int32Array(scored.length).fill(-1)\n const find = (index: number): number => {\n let root = index\n while (parent[root] !== root) root = parent[root]!\n let at = index\n while (parent[at] !== root) {\n const next = parent[at]!\n parent[at] = root\n at = next\n }\n return root\n }\n // Every local maximum could survive its saddle, so each is a test.\n let maxima = 0\n for (let index = 0; index < scored.length; index++) {\n if (adjacency[index]!.every((neighbour) => rank[neighbour]! > rank[index]!)) maxima += 1\n }\n const z = zQuantile(1 - BASIN_ALPHA / Math.max(1, maxima - 1))\n const survived = new Map<number, { saddle: number; persistence: number; threshold: number }>()\n for (const index of order) {\n let highest = -1\n for (const neighbour of adjacency[index]!) {\n if (parent[neighbour] === -1) continue\n if (highest === -1 || rank[neighbour]! < rank[highest]!) highest = neighbour\n }\n if (highest === -1) {\n parent[index] = index\n continue\n }\n parent[index] = find(highest)\n for (const neighbour of adjacency[index]!) {\n if (parent[neighbour] === -1) continue\n const mine = find(index)\n const theirs = find(neighbour)\n if (mine === theirs) continue\n const [high, low] = rank[mine]! < rank[theirs]! ? [mine, theirs] : [theirs, mine]\n const persistence = scored[low]!.score! - scored[index]!.score!\n const threshold = z * Math.sqrt(variance(low) + variance(index))\n if (persistence < threshold) {\n parent[low] = high\n } else if (!survived.has(low)) {\n survived.set(low, { saddle: index, persistence, threshold })\n }\n }\n }\n const peaks = [...new Set(order.map(find))].sort((left, right) => rank[left]! - rank[right]!)\n const basinOf = new Map(peaks.map((peak, basin) => [peak, basin]))\n const members = new Array<number>(peaks.length).fill(0)\n const byNode = new Map<string, number>()\n scored.forEach((node, index) => {\n const basin = basinOf.get(find(index))!\n byNode.set(node.nodeId, basin)\n members[basin]! += 1\n })\n for (const record of records) record.basin = byNode.get(record.nodeId) ?? null\n return {\n count: peaks.length,\n neighbours: k,\n localMaxima: maxima,\n z: round9(z),\n graphNodes: scored.length,\n graphAxes: space.axes,\n graphExplained: space.explained === null ? null : round9(space.explained),\n method: `${BASIN_METHOD}; pooled over ${degreesOfFreedom} degrees of freedom`,\n insufficient: null,\n peaks: peaks.map((peak, basin) => {\n const node = scored[peak]!\n const own = survived.get(peak) ?? null\n return {\n peak: {\n nodeId: node.nodeId,\n x: node.x!,\n y: node.y!,\n score: node.score!,\n pairs: node.pairs,\n },\n persistence: own === null ? null : round9(own.persistence),\n threshold: own === null ? null : round9(own.threshold),\n saddle: own === null ? null : scored[own.saddle]!.nodeId,\n nodes: members[basin]!,\n }\n }),\n }\n}\n\nconst BASIN_NEIGHBOURS = 6\n/** The basin graph's space: leading MDS axes up to this share of the positive\n * eigenvalue mass, and at most this many. */\nconst FULL_AXES_MASS = 0.8\nconst FULL_AXES_MAX = 8\n/** Family-wise rate of a spurious basin on a flat landscape. */\nconst BASIN_ALPHA = 0.05\n\n/**\n * Joins a graph's components into one (Borůvka): each round links every\n * component to its nearest point in another component by one edge, until\n * one component remains. Without it, two regions the k-nearest-neighbour\n * graph leaves apart would each count as a basin with no saddle to test.\n */\nfunction connectComponents(\n points: readonly (readonly number[])[],\n adjacency: number[][],\n): number[][] {\n const n = points.length\n const parent = Int32Array.from({ length: n }, (_, index) => index)\n const find = (index: number): number => {\n let root = index\n while (parent[root] !== root) root = parent[root]!\n while (parent[index] !== root) {\n const next = parent[index]!\n parent[index] = root\n index = next\n }\n return root\n }\n for (let a = 0; a < n; a++) for (const b of adjacency[a]!) parent[find(a)] = find(b)\n const edges = adjacency.map((list) => new Set(list))\n for (;;) {\n const component = Int32Array.from({ length: n }, (_, index) => find(index))\n const best = new Map<number, { a: number; b: number; distance: number }>()\n for (let a = 0; a < n; a++) {\n const own = component[a]!\n for (let b = 0; b < n; b++) {\n if (component[b] === own) continue\n const distance = euclidean(points[a]!, points[b]!)\n const known = best.get(own)\n if (!known || distance < known.distance) best.set(own, { a, b, distance })\n }\n }\n if (best.size === 0) break\n for (const { a, b } of best.values()) {\n edges[a]!.add(b)\n edges[b]!.add(a)\n parent[find(a)] = find(b)\n }\n }\n return edges.map((set) => [...set].sort((left, right) => left - right))\n}\n\n/**\n * The symmetric k-nearest-neighbour graph of points in any dimension: each\n * point joins its k nearest (ties by index) and every edge is kept in both\n * directions. Brute force, so callers keep n in the low thousands.\n */\nexport function nearestNeighbours(points: readonly (readonly number[])[], k: number): number[][] {\n const n = points.length\n const adjacency: Set<number>[] = Array.from({ length: n }, () => new Set<number>())\n if (n < 2 || k < 1) return adjacency.map(() => [])\n for (let index = 0; index < n; index++) {\n const best: Array<{ index: number; distance: number }> = []\n for (let other = 0; other < n; other++) {\n if (other === index) continue\n const distance = euclidean(points[index]!, points[other]!)\n if (best.length === k && distance >= best[k - 1]!.distance) continue\n best.push({ index: other, distance })\n best.sort((left, right) => left.distance - right.distance || left.index - right.index)\n if (best.length > k) best.length = k\n }\n for (const { index: other } of best) {\n adjacency[index]!.add(other)\n adjacency[other]!.add(index)\n }\n }\n return adjacency.map((set) => [...set].sort((left, right) => left - right))\n}\n\nfunction euclidean(left: readonly number[], right: readonly number[]): number {\n let sum = 0\n for (let d = 0; d < left.length; d++) sum += (left[d]! - (right[d] ?? 0)) ** 2\n return Math.sqrt(sum)\n}\n\n// ── Text ─────────────────────────────────────────────────────────────\n\nconst SHADES = ' .:-=+*#%@'\n\n/** The landscape as text for a terminal or a proposer's context: the same\n * numbers the view draws, with a coarse shaded map. */\nexport function formatLandscape(lens: GeometryLensResult<LandscapeData>): string {\n const { data } = lens\n const lines: string[] = []\n const { embedding } = data\n lines.push(\n `Landscape (${data.split} split, larger is better; ${embedding.name}: ${embedding.method})`,\n )\n lines.push(\n ` placed ${embedding.placed} of ${embedding.placed + embedding.unplaced} nodes by landmark MDS on ${plural(embedding.landmarks, 'landmark')}${embedding.landmarkDistance ? ` (landmarks lie a median ${fixed(embedding.landmarkDistance.median)} and at most ${fixed(embedding.landmarkDistance.max)} apart)` : ''}; two axes hold ${percent(embedding.explained)} of the positive eigenvalue mass (negative mass ${percent(embedding.negativeMass)})`,\n )\n const reasons = new Map<string, number>()\n for (const node of data.nodes) {\n if (node.unplaced) reasons.set(node.unplaced, (reasons.get(node.unplaced) ?? 0) + 1)\n }\n for (const [reason, count] of reasons) lines.push(` unplaced ${count}: ${reason}`)\n const methods = new Map<string, number>()\n for (const node of data.nodes) methods.set(node.method, (methods.get(node.method) ?? 0) + 1)\n lines.push(\n ` scores (improvement over the root on shared units): ${[\n 'bootstrap',\n 'descriptive',\n 'insufficient',\n 'none',\n ]\n .map((method) => `${methods.get(method) ?? 0} ${method}`)\n .join(', ')}`,\n )\n if (data.grid === null) {\n lines.push(` surface: insufficient: ${data.gridInsufficient}`)\n } else {\n const { grid } = data\n lines.push(\n ` surface: ${grid.columns}×${grid.rows} grid kriged from ${plural(grid.model.fitNodes, 'node')} (mean ${signed(grid.model.mean)}, prior sd ${fixed(Math.sqrt(grid.model.priorVariance))}, length scale ${fixed(grid.model.lengthScale)}); ${grid.supportedCells} of ${grid.columns * grid.rows} cells supported (posterior variance at most half the prior)`,\n )\n }\n const { basins } = data\n if (basins.count === null) {\n lines.push(` basins: insufficient: ${basins.insufficient}`)\n } else {\n lines.push(\n ` basins: ${basins.count} on the ${basins.neighbours}-nearest-neighbour graph of ${plural(basins.graphNodes, 'node')} in ${basins.graphAxes} MDS axes holding ${percent(basins.graphExplained)} of the distance structure (a lower peak counts when it stands ${fixed(basins.z!)} standard errors of the difference above its saddle, Bonferroni over ${basins.localMaxima} local ${basins.localMaxima === 1 ? 'maximum' : 'maxima'} at 5%)`,\n )\n basins.peaks.forEach((basin, index) => {\n const standing =\n basin.persistence === null\n ? index === 0\n ? 'the highest'\n : 'a separate region of the graph'\n : `persistence ${fixed(basin.persistence)} ≥ ${fixed(basin.threshold!)} over saddle ${basin.saddle}`\n lines.push(\n ` ${index + 1}. ${basin.peak.nodeId} ${signed(basin.peak.score)} on ${basin.peak.pairs} units at (${fixed(basin.peak.x)}, ${fixed(basin.peak.y)}), ${standing}; ${plural(basin.nodes, 'node')}`,\n )\n })\n }\n const { plateau } = data\n if (plateau.value === null) {\n lines.push(` plateau: insufficient: ${plateau.insufficient}`)\n } else {\n const verdict = plateau.value < 1 ? 'on a plateau' : 'still climbing'\n lines.push(\n ` plateau: ${fixed(plateau.value)}: the best improvement over the root rose ${signed(plateau.rise!)} across the last ${plateau.window} of ${plateau.accepted} accepted nodes, one standard error ${fixed(plateau.noise!)} (best ${plateau.best!.nodeId} on ${plateau.best!.pairs} units, ${plateau.degreesOfFreedom} pooled df): ${verdict}`,\n )\n }\n if (data.grid !== null) {\n const { grid } = data\n const present = grid.values.flat().filter((value): value is number => value !== null)\n const low = Math.min(...present)\n const high = Math.max(...present)\n const marks = new Map<number, string>()\n basins.peaks.forEach((basin, index) => {\n const cell = cellOf(grid, basin.peak.x, basin.peak.y)\n if (cell !== null) marks.set(cell, String((index + 1) % 10))\n })\n lines.push(\n ` map (top row is the highest y; shade ${JSON.stringify(SHADES)} runs from ${signed(low)} to ${signed(high)}; digits mark each basin's peak node):`,\n )\n for (let r = grid.rows - 1; r >= 0; r--) {\n let row = ''\n for (let c = 0; c < grid.columns; c++) {\n const mark = marks.get(r * grid.columns + c)\n const value = grid.values[r]![c]\n if (mark) row += mark\n else if (value === null || value === undefined) row += ' '\n else {\n const level = high > low ? (value - low) / (high - low) : 0.5\n row += SHADES[Math.min(SHADES.length - 1, Math.floor(level * SHADES.length))]!\n }\n }\n lines.push(` |${row}|`)\n }\n }\n return lines.join('\\n')\n}\n\nfunction percent(value: number | null): string {\n return value === null ? 'unknown' : `${Math.round(value * 1000) / 10}%`\n}\n\nfunction fixed(value: number): string {\n return value.toFixed(3)\n}\n\nfunction signed(value: number): string {\n return `${value >= 0 ? '+' : ''}${value.toFixed(3)}`\n}\n","/**\n * `metaSearch(searches)`: a search of searches (search-tree-design §12).\n *\n * Every search is one node. Its genome is the configuration that ran it: the\n * expansion policy and allocator its header declares (their names carry\n * their parameters, such as patience, operator weights and rung sizes), its\n * budget, and the proposer its edges and candidate-generation operations\n * name, with the proposer's model. Its score is the held-out lift its claim\n * measured, per known dollar of the whole search.\n *\n * The held-out lift is `estimateNode` of one node against the root on the\n * sealed test split, from the test cells themselves: the shipped node on\n * `ship`; on `hold`, the first finalist not decided invalid, in the claim's\n * order, which the claim fixed from selection data before any test cell ran.\n * A hold's measured lift counts rather than being dropped: keeping only the\n * searches whose test was significant would inflate a configuration's mean.\n * A search whose claim is open, missing, `test-cannot-resolve`, contradicted\n * by its own ledger (`verifySearchClaim`), held with no finalist tested, or\n * whose lift pairs fewer than 2 test units is unscored with its reason, never\n * 0, and every configuration reports how many of its searches were scored.\n *\n * Dollars are the search's committed spend: every cell and operation, the\n * claim's test cells included. An unknown-cost cell or operation leaves only a\n * floor, so that search's lift per dollar is a bound, not a value, and stays\n * out of every estimate. A search that recorded no spend has none either.\n *\n * Searches arrange into a forest by derivation (`derivedFrom`: a search that\n * started from a node of another) and containment (`containment`: a search\n * that ran inside a cell of another). A search contained in an outer search's\n * cell belongs to that cell's node: the outer node is its configuration, and\n * the outer node's lineage is the configuration's lineage.\n *\n * Configurations group searches with one genome and one objective (subject,\n * metric, direction). A configuration's lift per dollar summarizes its scored\n * searches as independent units with `summarizeSamples` (a percentile\n * bootstrap of the mean); a configuration with one scored search carries that\n * search's own paired interval, whose units are its test units. The signal\n * names the configuration with the largest estimate within one objective.\n */\n\nimport { estimateNode, seedFromDigest } from '../../campaign/estimate-node'\nimport { type SearchClaimVerification, verifySearchClaim } from '../../campaign/search-claim'\nimport type {\n NodeEstimate,\n SearchClaim,\n SearchCloseReason,\n SearchEstimateMethod,\n SearchLedgerHash,\n SearchModelIdentity,\n SearchProposerKind,\n SearchSourceRef,\n} from '../../campaign/search-ledger-types'\nimport type { SearchStateView } from '../../campaign/search-state'\nimport { compareCodeUnits, hashCanonical } from '../../ledger-core/canonical'\nimport {\n INSUFFICIENT_FROM,\n type LensResult,\n rankingSplit,\n type SampleSummary,\n summarizeSamples,\n} from './shared'\n\n/** The configuration that ran a search, as its ledger records it. */\nexport interface SearchPolicyGenome {\n /** `policy.expansion`: the policy's name with its parameters. A parameter\n * equal to the search's own seed (`seed=<n>`) reads `seed=<search>`: the\n * seed varies per search and is not a configuration choice. */\n expansion: string\n /** `policy.allocation`: the allocator's name with its rung sizes. */\n allocation: string\n budget: {\n maxUsd: number | null\n maxCells: number | null\n maxNodes: number | null\n maxConcurrency: number | null\n reservedClaimUsd: number\n }\n /** Every proposer a non-seed edge names, in canonical order. Unknown when\n * the search recorded no proposal, so its proposer cannot be read. */\n proposers:\n | Array<{ kind: SearchProposerKind; name: string; source: SearchSourceRef }>\n | {\n unknown: string\n }\n /** What ran the candidate-generation operations (a proposer's model, or\n * deterministic code), in canonical order; unknown with no such operation. */\n proposerExecution:\n | Array<\n | { kind: 'model'; model: SearchModelIdentity }\n | { kind: 'deterministic'; source: SearchSourceRef }\n >\n | { unknown: string }\n}\n\n/** Why a search has no lift to score. */\nexport type MetaSearchUnscoredReason =\n | 'open'\n | 'no-claim'\n | 'claim-mismatch'\n | 'test-cannot-resolve'\n | 'no-valid-finalist'\n | 'insufficient'\n\nexport interface MetaSearchSpend {\n knownUsd: number\n /** Proven lower bounds of unknown costs. */\n floorUsd: number\n /** Cells and operations whose cost is unknown. */\n unknownCost: number\n}\n\n/** A search's lift per dollar: a value, a bound when some cost is only a\n * floor, or unknown. */\nexport type MetaSearchLiftPerUsd =\n | {\n status: 'known'\n value: number\n /** The lift's interval divided by the known spend, which is exact. */\n interval: [number, number] | null\n }\n | {\n status: 'bound'\n /** The lift divided by the committed spend, a lower bound on the true\n * spend: the true value lies at or below it for a gain and at or above\n * it for a loss. */\n value: number\n bound: 'at-most' | 'at-least'\n reason: string\n }\n | { status: 'unknown'; reason: string }\n\nexport type MetaSearchScore =\n | {\n status: 'scored'\n decision: 'ship' | 'hold'\n /** The node whose held-out lift this is. */\n nodeId: string\n /** The node against the root on the test split. */\n estimate: NodeEstimate\n /** `estimate.delta` oriented so a gain is positive, in the metric's units. */\n lift: number\n /** `estimate.interval`, oriented the same way; null below 6 units. */\n liftInterval: [number, number] | null\n spend: MetaSearchSpend\n liftPerUsd: MetaSearchLiftPerUsd\n }\n | {\n status: 'unscored'\n decision: SearchClaim['decision'] | null\n reason: MetaSearchUnscoredReason\n detail: string\n spend: MetaSearchSpend\n }\n\n/** How a search relates to its parent in the forest. */\nexport type MetaSearchParent =\n | {\n relation: 'derived'\n searchId: string\n /** The parent's node this search started from. */\n nodeId: string\n /** The parent is among the searches the lens read. */\n present: boolean\n }\n | {\n relation: 'contained'\n searchId: string\n cellId: string\n attempt: number\n /** The outer node whose cell ran this search; null when the outer\n * search was not read. */\n nodeId: string | null\n present: boolean\n }\n\nexport interface MetaSearchEntry {\n searchId: string\n subject: string\n objective: { metric: string; direction: 'maximize' | 'minimize' }\n /** `subject · metric (direction)`: searches are compared only within one. */\n objectiveKey: string\n status: 'open' | 'closed'\n closeReason: SearchCloseReason | null\n genome: SearchPolicyGenome\n genomeDigest: SearchLedgerHash\n seed: number\n rootArtifactDigest: string | null\n nodes: number\n cells: { settled: number; test: number }\n claim: {\n decision: SearchClaim['decision']\n selected: string | null\n verification: 'verified' | 'mismatch' | 'unknown'\n reason: string\n } | null\n score: MetaSearchScore\n parent: MetaSearchParent | null\n children: string[]\n /** Edges from the forest's root; 0 for a root. */\n depth: number\n /** The search's own tree, for a glyph: `[nodeId, primaryParentId, status]`\n * in registration order, the first `glyphNodes`. */\n glyph: { nodes: Array<[string, string | null, string | null]>; omitted: number }\n}\n\n/** A configuration's lift per known dollar across its scored searches. */\nexport interface MetaSearchConfigurationEstimate {\n /** `searches`: the scored searches are the units. `test-units`: one scored\n * search, so its own test units are. */\n basis: 'searches' | 'test-units'\n n: number\n value: number | null\n method: SearchEstimateMethod\n interval: [number, number] | null\n /** How the interval was computed; null without one. */\n intervalMethod: 'percentile-bootstrap-of-mean' | 'paired-delta-test-over-usd' | null\n}\n\nexport interface MetaSearchConfiguration {\n genomeDigest: SearchLedgerHash\n objectiveKey: string\n genome: SearchPolicyGenome\n searches: string[]\n decisions: { ship: number; hold: number; 'test-cannot-resolve': number; none: number }\n /** Searches with a known lift per dollar. */\n scored: number\n /** Searches whose lift per dollar is a bound. */\n bounded: number\n unscored: Partial<Record<MetaSearchUnscoredReason, number>>\n estimate: MetaSearchConfigurationEstimate\n /** Outer-search nodes whose cells ran this configuration's searches, with\n * the outer node's parent configuration and its paired estimate against it\n * on the outer search's ranking split. */\n outerNodes: Array<{\n searchId: string\n nodeId: string\n parentNodeId: string | null\n parentGenomeDigest: SearchLedgerHash | null\n againstParent: NodeEstimate | null\n }>\n}\n\nexport interface MetaSearchData {\n searches: MetaSearchEntry[]\n roots: string[]\n /** Best first: by estimate, then configurations without one. */\n configurations: MetaSearchConfiguration[]\n objectives: string[]\n /** The objective the signal ranks within; null when none could be chosen. */\n signalObjective: string | null\n}\n\n/** The signal: the configuration with the largest estimated lift per known\n * dollar within one objective, with its interval, its method and its n. */\nexport interface BestPolicyConfiguration {\n /** Lift per known dollar of the best configuration; null when none has one. */\n liftPerUsd: number | null\n objectiveKey: string | null\n genomeDigest: SearchLedgerHash | null\n genome: SearchPolicyGenome | null\n interval: [number, number] | null\n method: SearchEstimateMethod | null\n intervalMethod: MetaSearchConfigurationEstimate['intervalMethod']\n basis: MetaSearchConfigurationEstimate['basis'] | null\n n: number\n /** The configuration's searches, and how many of them have a known lift\n * per dollar: the rest are unscored or bounded, never counted as 0. */\n searches: number\n scored: number\n /** An outer-search node whose artifact runs this configuration, when an\n * outer search ran it: the runnable configuration a caller derives the next\n * search from. Null for a configuration only free-standing searches ran. */\n outerNode: { searchId: string; nodeId: string } | null\n /** Why the value is what it is, including why it is null. */\n reason: string\n}\n\nexport interface MetaSearchOptions {\n /** Nodes of each search's own tree carried for its glyph. Default 64. */\n glyphNodes?: number\n /** The objective key the signal ranks within. Default: the one objective\n * whose searches have a known lift per dollar; with several, the signal is\n * null until one is named. */\n objective?: string\n}\n\n/** The signal's name, as a policy or a view reads it. */\nexport const META_SEARCH_SIGNAL = 'metaSearch.bestPolicyConfiguration'\n\nconst DEFAULT_GLYPH_NODES = 64\n\n/**\n * Every rule the per-search score depends on. Its digest is the score's\n * revision, which an outer search pins as its judge, so an outer climb's\n * cells and the lens report one number.\n */\nconst META_SEARCH_SCORE_DEFINITION = {\n name: 'tangle.meta-search-score.2026-09',\n node: 'the claim selection on ship; on hold, the first finalist in claim order not decided invalid',\n lift: 'estimateNode(node, against root, split test), oriented so a gain is positive',\n unscored: [\n 'open',\n 'no claim',\n 'claim the ledger contradicts (verifySearchClaim mismatch)',\n 'test-cannot-resolve',\n 'hold with no finalist tested',\n 'fewer than 2 shared test units',\n ],\n dollars: 'committed spend of every cell and operation, claim cells included',\n unknownCost: 'a floor only: the lift per dollar is a bound and enters no estimate',\n} as const\n\n/** The per-search score `metaSearchScore` computes. An outer search names it\n * as its objective's judge. */\nexport const META_SEARCH_SCORE_SOURCE: SearchSourceRef = {\n uri: 'npm:@tangle-network/agent-eval#metaSearchScore',\n revision: hashCanonical(META_SEARCH_SCORE_DEFINITION),\n}\n\n/**\n * The genome of a search: the configuration its ledger records. Declared\n * parts come from the header; the proposer comes from what the edges and\n * candidate-generation operations name, because the header declares none.\n */\nexport function searchPolicyGenome(state: SearchStateView): SearchPolicyGenome {\n const header = state.header\n if (!header) throw new Error(`search ${state.searchId} has not been opened`)\n const { maxUsd, maxCells, maxNodes, maxConcurrency, reservedClaimUsd } = header.budget\n const proposers = new Map<\n string,\n { kind: SearchProposerKind; name: string; source: SearchSourceRef }\n >()\n const operations = new Set<string>()\n for (const edge of state.edges()) {\n if (!edge.proposer) continue\n const { kind, name, source, operationId } = edge.proposer\n const proposer = { kind, name, source }\n proposers.set(hashCanonical(proposer), proposer)\n if (operationId !== null) operations.add(operationId)\n }\n const executions = new Map<\n string,\n | { kind: 'model'; model: SearchModelIdentity }\n | { kind: 'deterministic'; source: SearchSourceRef }\n >()\n for (const operationId of operations) {\n const execution = state.operation(operationId)?.execution\n if (!execution) continue\n const entry =\n execution.kind === 'model'\n ? { kind: 'model' as const, model: execution.model }\n : { kind: 'deterministic' as const, source: execution.source }\n executions.set(hashCanonical(entry), entry)\n }\n return {\n expansion: withoutSearchSeed(header.policy.expansion, header.policy.seed),\n allocation: withoutSearchSeed(header.policy.allocation, header.policy.seed),\n budget: { maxUsd, maxCells, maxNodes, maxConcurrency, reservedClaimUsd },\n proposers:\n proposers.size > 0\n ? sortedValues(proposers)\n : { unknown: 'the search recorded no proposal, so its proposer is not in the ledger' },\n proposerExecution:\n executions.size > 0\n ? sortedValues(executions)\n : { unknown: 'no recorded candidate-generation operation names what ran the proposer' },\n }\n}\n\n/**\n * A search's held-out lift per known dollar, from its claim and its test\n * cells. Pure; it reads the test split, so a policy view (which holds no test\n * cells) cannot call it; an outer search reads it from a closed inner search.\n */\nexport function metaSearchScore(state: SearchStateView): MetaSearchScore {\n return scoreSearch(state, state.closed?.claim ? verifySearchClaim(state) : null)\n}\n\nfunction scoreSearch(\n state: SearchStateView,\n verification: SearchClaimVerification | null,\n): MetaSearchScore {\n const header = state.header\n if (!header) throw new Error(`search ${state.searchId} has not been opened`)\n const { spend: audit } = state.audit\n const spend: MetaSearchSpend = {\n knownUsd: audit.knownUsd,\n floorUsd: audit.floorUsd,\n unknownCost: audit.unknownCostCells + audit.unknownCostOperations,\n }\n const unscored = (\n reason: MetaSearchUnscoredReason,\n detail: string,\n decision: SearchClaim['decision'] | null = null,\n ): MetaSearchScore => ({ status: 'unscored', decision, reason, detail, spend })\n\n const closed = state.closed\n if (!closed) return unscored('open', 'the search is open; its claim is made when it closes')\n const claim = closed.claim\n if (!claim) {\n return unscored(\n 'no-claim',\n `the search closed (${closed.reason}) without a claim on a test split`,\n )\n }\n if (verification?.status === 'mismatch') {\n return unscored(\n 'claim-mismatch',\n `the claim differs from what its ledger supports: ${verification.differences.join('; ')}`,\n claim.decision,\n )\n }\n if (claim.decision === 'test-cannot-resolve') {\n return unscored('test-cannot-resolve', claim.reason, claim.decision)\n }\n const root = state.rootNodeId!\n const nodeId =\n claim.decision === 'ship'\n ? claim.selected\n : (claim.finalists.find((finalist) => state.node(finalist.nodeId)?.status !== 'invalid')\n ?.nodeId ?? null)\n if (nodeId === null || nodeId === root) {\n return unscored(\n 'no-valid-finalist',\n claim.finalists.length === 0\n ? `hold: no finalist went to test (${claim.reason})`\n : `hold: every finalist was decided invalid (${claim.finalists.length})`,\n claim.decision,\n )\n }\n const estimate = estimateNode(state, nodeId, { against: root, split: 'test' })\n if (estimate.delta === null) {\n return unscored(\n 'insufficient',\n `${nodeId} and the root share ${estimate.pairs} scored test unit${estimate.pairs === 1 ? '' : 's'}; a lift needs 2`,\n claim.decision,\n )\n }\n const maximize = header.objective.direction === 'maximize'\n const lift = orient(estimate.delta, maximize)\n const liftInterval = estimate.interval ? orientInterval(estimate.interval, maximize) : null\n return {\n status: 'scored',\n decision: claim.decision,\n nodeId,\n estimate,\n lift,\n liftInterval,\n spend,\n liftPerUsd: liftPerUsd(lift, liftInterval, spend),\n }\n}\n\n/** The lens: every search as a node of a search of searches. */\nexport function metaSearch(\n searches: readonly SearchStateView[],\n options: MetaSearchOptions = {},\n): LensResult<MetaSearchData, BestPolicyConfiguration> {\n const glyphNodes = options.glyphNodes ?? DEFAULT_GLYPH_NODES\n if (!Number.isSafeInteger(glyphNodes) || glyphNodes < 0) {\n throw new TypeError(`metaSearch: glyphNodes must be a non-negative integer, got ${glyphNodes}`)\n }\n const byId = new Map<string, SearchStateView>()\n for (const state of searches) {\n if (!state.header) throw new Error(`metaSearch: search ${state.searchId} has not been opened`)\n if (byId.has(state.searchId)) {\n throw new Error(`metaSearch: search ${state.searchId} was given twice`)\n }\n byId.set(state.searchId, state)\n }\n\n const entries = searches.map((state) => entry(state, byId, glyphNodes))\n const entryById = new Map(entries.map((item) => [item.searchId, item]))\n for (const item of entries) {\n if (item.parent?.present) entryById.get(item.parent.searchId)!.children.push(item.searchId)\n }\n const roots = entries.filter((item) => !item.parent?.present).map((item) => item.searchId)\n const assignDepth = (searchId: string, depth: number, seen: Set<string>): void => {\n if (seen.has(searchId)) return\n seen.add(searchId)\n const item = entryById.get(searchId)!\n item.depth = depth\n for (const child of item.children) assignDepth(child, depth + 1, seen)\n }\n const seen = new Set<string>()\n for (const root of roots) assignDepth(root, 0, seen)\n\n const configurations = configure(entries, byId)\n const objectives = [...new Set(entries.map((item) => item.objectiveKey))].sort(compareCodeUnits)\n const { objective, value } = best(configurations, objectives, options.objective)\n return {\n data: { searches: entries, roots, configurations, objectives, signalObjective: objective },\n signal: { name: META_SEARCH_SIGNAL, value },\n }\n}\n\nfunction entry(\n state: SearchStateView,\n byId: ReadonlyMap<string, SearchStateView>,\n glyphNodes: number,\n): MetaSearchEntry {\n const header = state.header!\n const genome = searchPolicyGenome(state)\n const closed = state.closed\n let claim: MetaSearchEntry['claim'] = null\n const verification = closed?.claim ? verifySearchClaim(state) : null\n if (closed?.claim) {\n claim = {\n decision: closed.claim.decision,\n selected: closed.claim.selected,\n verification: verification?.status ?? 'unknown',\n reason: closed.claim.reason,\n }\n }\n const nodes = state.nodes()\n const cells = state.cells()\n return {\n searchId: state.searchId,\n subject: header.subject,\n objective: { metric: header.objective.metric, direction: header.objective.direction },\n objectiveKey: objectiveKey(header),\n status: closed ? 'closed' : 'open',\n closeReason: closed?.reason ?? null,\n genome,\n genomeDigest: hashCanonical(genome),\n seed: header.policy.seed,\n rootArtifactDigest: nodes[0]?.artifactDigest ?? null,\n nodes: nodes.length,\n cells: {\n settled: state.audit.cells.settled,\n test: cells.filter((cell) => cell.split === 'test').length,\n },\n claim,\n score: scoreSearch(state, verification),\n parent: parentOf(state, byId),\n children: [],\n depth: 0,\n glyph: {\n nodes: nodes\n .slice(0, glyphNodes)\n .map((node): [string, string | null, string | null] => [\n node.nodeId,\n node.primaryParentId,\n node.status,\n ]),\n omitted: Math.max(0, nodes.length - glyphNodes),\n },\n }\n}\n\n/** `subject · metric (direction)`: the key searches are compared within. */\nexport function objectiveKey(header: NonNullable<SearchStateView['header']>): string {\n return `${header.subject} · ${header.objective.metric} (${header.objective.direction})`\n}\n\nfunction parentOf(\n state: SearchStateView,\n byId: ReadonlyMap<string, SearchStateView>,\n): MetaSearchParent | null {\n const header = state.header!\n if (header.containment) {\n const { searchId, cellId, attempt } = header.containment\n const outer = byId.get(searchId)\n return {\n relation: 'contained',\n searchId,\n cellId,\n attempt,\n nodeId: outer?.cell(cellId)?.nodeId ?? null,\n present: outer !== undefined,\n }\n }\n if (header.derivedFrom) {\n const { searchId, nodeId } = header.derivedFrom\n return { relation: 'derived', searchId, nodeId, present: byId.has(searchId) }\n }\n return null\n}\n\nfunction configure(\n entries: readonly MetaSearchEntry[],\n byId: ReadonlyMap<string, SearchStateView>,\n): MetaSearchConfiguration[] {\n const groups = new Map<string, MetaSearchEntry[]>()\n for (const item of entries) {\n const key = configurationKey(item.objectiveKey, item.genomeDigest)\n const group = groups.get(key)\n if (group) group.push(item)\n else groups.set(key, [item])\n }\n // The configuration each outer node ran: the genome of the searches its\n // cells contain.\n const genomeOfOuterNode = new Map<string, SearchLedgerHash>()\n for (const item of entries) {\n if (item.parent?.relation === 'contained' && item.parent.nodeId !== null) {\n genomeOfOuterNode.set(`${item.parent.searchId}\\u0000${item.parent.nodeId}`, item.genomeDigest)\n }\n }\n const configurations = [...groups.values()].map((group): MetaSearchConfiguration => {\n const first = group[0]!\n const decisions = { ship: 0, hold: 0, 'test-cannot-resolve': 0, none: 0 }\n const unscored: MetaSearchConfiguration['unscored'] = {}\n const values: number[] = []\n let single: MetaSearchConfigurationEstimate | null = null\n let bounded = 0\n for (const item of group) {\n decisions[item.claim?.decision ?? 'none'] += 1\n const score = item.score\n if (score.status === 'unscored') {\n unscored[score.reason] = (unscored[score.reason] ?? 0) + 1\n continue\n }\n if (score.liftPerUsd.status === 'bound') bounded += 1\n if (score.liftPerUsd.status !== 'known') continue\n values.push(score.liftPerUsd.value)\n single = {\n basis: 'test-units',\n n: score.estimate.pairs,\n value: score.liftPerUsd.value,\n method: score.estimate.method,\n interval: score.liftPerUsd.interval,\n intervalMethod: score.liftPerUsd.interval ? 'paired-delta-test-over-usd' : null,\n }\n }\n const estimate: MetaSearchConfigurationEstimate =\n values.length === 1 && single\n ? single\n : fromSummary(summarizeSamples(values, seedFromDigest(first.genomeDigest)))\n const outerNodes = new Map<string, MetaSearchConfiguration['outerNodes'][number]>()\n for (const item of group) {\n const parent = item.parent\n if (parent?.relation !== 'contained' || parent.nodeId === null) continue\n const key = `${parent.searchId}\\u0000${parent.nodeId}`\n if (outerNodes.has(key)) continue\n const outer = byId.get(parent.searchId)!\n const node = outer.node(parent.nodeId)!\n const parentNodeId = node.primaryParentId\n outerNodes.set(key, {\n searchId: parent.searchId,\n nodeId: parent.nodeId,\n parentNodeId,\n parentGenomeDigest:\n parentNodeId === null\n ? null\n : (genomeOfOuterNode.get(`${parent.searchId}\\u0000${parentNodeId}`) ?? null),\n againstParent:\n parentNodeId === null\n ? null\n : estimateNode(outer, parent.nodeId, {\n against: parentNodeId,\n split: rankingSplit(outer),\n }),\n })\n }\n return {\n genomeDigest: first.genomeDigest,\n objectiveKey: first.objectiveKey,\n genome: first.genome,\n searches: group.map((item) => item.searchId),\n decisions,\n scored: values.length,\n bounded,\n unscored,\n estimate,\n outerNodes: [...outerNodes.values()],\n }\n })\n return configurations.sort(\n (left, right) =>\n rankValue(right.estimate.value) - rankValue(left.estimate.value) ||\n right.scored - left.scored ||\n compareCodeUnits(left.objectiveKey, right.objectiveKey) ||\n compareCodeUnits(left.genomeDigest, right.genomeDigest),\n )\n}\n\nfunction best(\n configurations: readonly MetaSearchConfiguration[],\n objectives: readonly string[],\n requested: string | undefined,\n): { objective: string | null; value: BestPolicyConfiguration } {\n const empty = (\n objective: string | null,\n reason: string,\n ): { objective: string | null; value: BestPolicyConfiguration } => ({\n objective,\n value: {\n liftPerUsd: null,\n objectiveKey: objective,\n genomeDigest: null,\n genome: null,\n interval: null,\n method: null,\n intervalMethod: null,\n basis: null,\n n: 0,\n searches: 0,\n scored: 0,\n outerNode: null,\n reason,\n },\n })\n if (configurations.length === 0) return empty(null, 'no search was given')\n const measured = [\n ...new Set(\n configurations\n .filter((item) => item.estimate.value !== null)\n .map((item) => item.objectiveKey),\n ),\n ].sort(compareCodeUnits)\n let objective: string\n if (requested !== undefined) {\n if (!objectives.includes(requested)) {\n return empty(\n requested,\n `no search given has objective ${requested}; the searches have ${objectives.join('; ')}`,\n )\n }\n objective = requested\n } else if (measured.length > 1) {\n return empty(\n null,\n `searches with a known lift per dollar span ${measured.length} objectives (${measured.join('; ')}); a lift in one metric does not compare with another, so name one`,\n )\n } else {\n objective = measured[0] ?? (objectives.length === 1 ? objectives[0]! : '')\n if (objective === '') {\n return empty(\n null,\n `no configuration has a known lift per dollar, across ${objectives.length} objectives`,\n )\n }\n }\n const within = configurations.filter((item) => item.objectiveKey === objective)\n const withValue = within.filter((item) => item.estimate.value !== null)\n const top = withValue[0]\n if (!top) {\n const unscored = within.reduce(\n (total, item) =>\n total + Object.values(item.unscored).reduce((sum, count) => sum + (count ?? 0), 0),\n 0,\n )\n const bounded = within.reduce((total, item) => total + item.bounded, 0)\n return empty(\n objective,\n `no configuration of ${objective} has a known lift per dollar: ${unscored} unscored search${unscored === 1 ? '' : 'es'} and ${bounded} with only a spend floor`,\n )\n }\n const { estimate } = top\n const runnerUp = withValue[1]\n const coverage = `${top.scored} of ${top.searches.length} of its searches scored`\n return {\n objective,\n value: {\n liftPerUsd: estimate.value,\n objectiveKey: objective,\n genomeDigest: top.genomeDigest,\n genome: top.genome,\n interval: estimate.interval,\n method: estimate.method,\n intervalMethod: estimate.intervalMethod,\n basis: estimate.basis,\n n: estimate.n,\n searches: top.searches.length,\n scored: top.scored,\n outerNode: top.outerNodes[0]\n ? { searchId: top.outerNodes[0].searchId, nodeId: top.outerNodes[0].nodeId }\n : null,\n reason:\n runnerUp === undefined\n ? `the only configuration with a known lift per dollar (${estimate.method}, ${estimate.basis} n=${estimate.n}; ${coverage})`\n : `the largest of ${withValue.length} configurations by estimated lift per dollar (${estimate.method}, ${estimate.basis} n=${estimate.n}; ${coverage}); a point ranking, not a test`,\n },\n }\n}\n\nfunction liftPerUsd(\n lift: number,\n interval: [number, number] | null,\n spend: MetaSearchSpend,\n): MetaSearchLiftPerUsd {\n const committed = spend.knownUsd + spend.floorUsd\n if (spend.unknownCost > 0) {\n if (committed <= 0) {\n return {\n status: 'unknown',\n reason: `${spend.unknownCost} cost${spend.unknownCost === 1 ? ' is' : 's are'} unknown with no proven floor`,\n }\n }\n return {\n status: 'bound',\n value: lift / committed,\n bound: lift >= 0 ? 'at-most' : 'at-least',\n reason: `${spend.unknownCost} cost${spend.unknownCost === 1 ? ' is' : 's are'} known only as a floor; $${round(committed)} is the least the search spent`,\n }\n }\n if (spend.knownUsd <= 0) {\n return {\n status: 'unknown',\n reason: 'the search recorded no spend, so a lift per dollar is undefined',\n }\n }\n return {\n status: 'known',\n value: lift / spend.knownUsd,\n interval: interval ? [interval[0] / spend.knownUsd, interval[1] / spend.knownUsd] : null,\n }\n}\n\nfunction fromSummary(summary: SampleSummary): MetaSearchConfigurationEstimate {\n return {\n basis: 'searches',\n n: summary.n,\n value: summary.mean,\n method: summary.n < 2 ? 'none' : summary.method,\n interval: summary.interval,\n intervalMethod: summary.interval ? 'percentile-bootstrap-of-mean' : null,\n }\n}\n\n// ── text form ────────────────────────────────────────────────────────\n\nexport interface MetaSearchTextOptions {\n /** Searches listed under each outer node or parent before the rest are\n * counted. Default 5. */\n searchesPerGroup?: number\n}\n\n/**\n * The lens as text, for an agent: the signal, every configuration best first\n * with its coverage and interval, and the forest of searches with contained\n * searches grouped under the outer node that ran them. `agent-eval search show\n * --meta` prints it.\n */\nexport function renderMetaSearchText(\n result: LensResult<MetaSearchData, BestPolicyConfiguration>,\n options: MetaSearchTextOptions = {},\n): string {\n const perGroup = options.searchesPerGroup ?? 5\n const { data, signal } = result\n const lines: string[] = []\n const contained = data.searches.filter((item) => item.parent?.relation === 'contained').length\n const derived = data.searches.filter((item) => item.parent?.relation === 'derived').length\n lines.push(\n `meta-search: ${plural(data.searches.length, 'search', 'searches')} (${contained} contained, ${derived} derived) in ${plural(data.objectives.length, 'objective')}, ${plural(data.configurations.length, 'configuration')}`,\n )\n const value = signal.value\n lines.push(\n value.liftPerUsd === null\n ? `${signal.name}: unknown — ${value.reason}`\n : `${signal.name}: ${value.genomeDigest!.slice(0, 19)} lift per known $ ${formatNumber(value.liftPerUsd)} ${formatInterval(value.interval, value.intervalMethod)} (${value.method}, ${value.basis} n=${value.n}); ${value.reason}`,\n )\n // One genome can run under several objectives, so a configuration is keyed\n // by both.\n const index = new Map(\n data.configurations.map((item, position) => [\n configurationKey(item.objectiveKey, item.genomeDigest),\n position,\n ]),\n )\n for (const objective of data.objectives) {\n lines.push('', `configurations of ${objective}, best first:`)\n for (const configuration of data.configurations) {\n if (configuration.objectiveKey !== objective) continue\n lines.push(...configurationLines(configuration, index))\n }\n }\n lines.push('', 'searches, by derivation and containment:')\n const byId = new Map(data.searches.map((item) => [item.searchId, item]))\n const walk = (searchId: string, depth: number): void => {\n const item = byId.get(searchId)!\n const pad = ' '.repeat(depth + 1)\n lines.push(`${pad}${searchLine(item, index)}`)\n const derivedChildren = item.children.filter(\n (child) => byId.get(child)!.parent?.relation === 'derived',\n )\n for (const child of derivedChildren) walk(child, depth + 1)\n const groups = new Map<string, MetaSearchEntry[]>()\n for (const child of item.children) {\n const childItem = byId.get(child)!\n if (childItem.parent?.relation !== 'contained') continue\n const key = childItem.parent.nodeId ?? '(unknown node)'\n const group = groups.get(key)\n if (group) group.push(childItem)\n else groups.set(key, [childItem])\n }\n for (const [nodeId, group] of groups) {\n const shown = group.slice(0, perGroup)\n const tally = decisionTally(group)\n lines.push(\n `${pad} node ${nodeId}: ${plural(group.length, 'contained search', 'contained searches')} (${tally})`,\n )\n for (const child of shown) walk(child.searchId, depth + 2)\n if (group.length > shown.length) {\n lines.push(`${' '.repeat(depth + 3)}… ${group.length - shown.length} more`)\n }\n }\n }\n for (const root of data.roots) walk(root, 0)\n return lines.join('\\n')\n}\n\nfunction configurationLines(\n configuration: MetaSearchConfiguration,\n index: ReadonlyMap<string, number>,\n): string[] {\n const { estimate, genome } = configuration\n const decisions = Object.entries(configuration.decisions)\n .filter(([, count]) => count > 0)\n .map(([decision, count]) => `${decision} ${count}`)\n .join(', ')\n const unscored = Object.entries(configuration.unscored)\n .map(([reason, count]) => `${reason} ${count}`)\n .join(', ')\n const value =\n estimate.value === null\n ? 'lift per known $: unknown'\n : `lift per known $ ${formatNumber(estimate.value)} ${formatInterval(estimate.interval, estimate.intervalMethod)} (${estimate.method}, ${estimate.basis} n=${estimate.n})`\n const lines = [\n ` #${index.get(configurationKey(configuration.objectiveKey, configuration.genomeDigest))! + 1} ${configuration.genomeDigest.slice(0, 19)} ${genomeLine(genome)}`,\n ` ${plural(configuration.searches.length, 'search', 'searches')}: ${decisions}; scored ${configuration.scored}${configuration.bounded > 0 ? `, spend floor only ${configuration.bounded}` : ''}${unscored ? `, unscored: ${unscored}` : ''}; ${value}`,\n ]\n for (const outer of configuration.outerNodes) {\n const against = outer.againstParent\n const parentIndex =\n outer.parentGenomeDigest === null\n ? undefined\n : index.get(configurationKey(configuration.objectiveKey, outer.parentGenomeDigest))\n lines.push(\n against === null\n ? ` outer node ${outer.nodeId} in ${outer.searchId}: the outer root`\n : ` outer node ${outer.nodeId} in ${outer.searchId}, from ${parentIndex === undefined ? outer.parentNodeId : `#${parentIndex + 1}`}: ${estimateText(against)}`,\n )\n }\n return lines\n}\n\nfunction searchLine(item: MetaSearchEntry, index: ReadonlyMap<string, number>): string {\n const claim = item.claim\n ? `claim ${item.claim.decision} (${item.claim.verification})`\n : 'no claim'\n const configuration = index.get(configurationKey(item.objectiveKey, item.genomeDigest))\n const score = item.score\n const scoreText =\n score.status === 'unscored'\n ? `unscored: ${score.reason} — ${score.detail}`\n : `lift ${formatNumber(score.lift)} ${formatInterval(score.liftInterval, score.liftInterval ? 'paired-delta-test' : null)} on ${score.estimate.pairs} test units (${score.estimate.method}); ${liftPerUsdText(score.liftPerUsd)}`\n const relation =\n item.parent === null\n ? ''\n : item.parent.relation === 'derived'\n ? ` derived from ${item.parent.searchId}/${item.parent.nodeId}${item.parent.present ? '' : ' (not given)'};`\n : item.parent.present\n ? ''\n : ` contained in ${item.parent.searchId} cell ${item.parent.cellId} (not given);`\n return `${item.searchId} [${item.status}${item.closeReason ? `: ${item.closeReason}` : ''}; ${claim}; config #${configuration === undefined ? '?' : configuration + 1}; ${item.nodes} nodes, ${item.cells.settled} cells, $${round(item.score.spend.knownUsd)} known${item.score.spend.unknownCost > 0 ? ` + $${round(item.score.spend.floorUsd)} floor over ${item.score.spend.unknownCost} unknown` : ''}]${relation} ${scoreText}`\n}\n\nfunction genomeLine(genome: SearchPolicyGenome): string {\n const budget = Object.entries(genome.budget)\n .filter(([, value]) => value !== null && value !== 0)\n .map(([key, value]) => `${key}=${value}`)\n .join(' ')\n const proposers = Array.isArray(genome.proposers)\n ? genome.proposers.map((proposer) => `${proposer.kind}:${proposer.name}`).join(', ')\n : 'unknown'\n const execution = Array.isArray(genome.proposerExecution)\n ? genome.proposerExecution\n .map((item) =>\n item.kind === 'model'\n ? `model ${item.model.provider}/${'snapshot' in item.model ? item.model.snapshot : `${item.model.alias} (snapshot unknown)`}`\n : 'deterministic',\n )\n .join(', ')\n : 'unknown'\n return `expansion=${genome.expansion} allocation=${genome.allocation}${budget ? ` ${budget}` : ''} proposer=${proposers} (${execution})`\n}\n\nfunction decisionTally(group: readonly MetaSearchEntry[]): string {\n const counts = new Map<string, number>()\n for (const item of group) {\n const key =\n item.score.status === 'scored'\n ? `${item.score.decision} scored`\n : `${item.claim?.decision ?? 'no claim'} unscored`\n counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n return [...counts.entries()]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([key, count]) => `${key} ${count}`)\n .join(', ')\n}\n\nfunction estimateText(estimate: NodeEstimate): string {\n if (estimate.delta === null) return `unknown (${plural(estimate.pairs, 'shared unit')})`\n if (estimate.method === 'insufficient') {\n return `${formatSigned(estimate.delta)} (insufficient: ${estimate.pairs} of ${INSUFFICIENT_FROM} units)`\n }\n return `${formatSigned(estimate.delta)} ${formatInterval(estimate.interval, estimate.interval ? 'paired-delta-test' : null)} (${estimate.method}, ${estimate.pairs} ${estimate.split} units)`\n}\n\nfunction liftPerUsdText(value: MetaSearchLiftPerUsd): string {\n if (value.status === 'unknown') return `per $: unknown (${value.reason})`\n if (value.status === 'bound') {\n return `per $: ${value.bound} ${formatNumber(value.value)} (${value.reason})`\n }\n return `per $: ${formatNumber(value.value)}`\n}\n\nfunction formatInterval(interval: [number, number] | null, method: string | null): string {\n if (interval === null) return '[no interval]'\n return `[${formatNumber(interval[0])}, ${formatNumber(interval[1])}]${method ? ` ${method}` : ''}`\n}\n\nfunction formatNumber(value: number): string {\n if (value === 0) return '0'\n const magnitude = Math.abs(value)\n return magnitude >= 0.01 ? value.toFixed(4) : value.toPrecision(3)\n}\n\nfunction formatSigned(value: number): string {\n return value > 0 ? `+${formatNumber(value)}` : formatNumber(value)\n}\n\nfunction plural(count: number, one: string, many = `${one}s`): string {\n return `${count} ${count === 1 ? one : many}`\n}\n\n// ── helpers ──────────────────────────────────────────────────────────\n\n/** A policy or allocator name carries `seed=<n>` when it is seeded from the\n * search's own seed; the genome names it `seed=<search>` so searches of one\n * configuration on different seeds share a genome. */\nfunction withoutSearchSeed(name: string, seed: number): string {\n return name.replace(new RegExp(`\\\\bseed=${seed}(?![\\\\d.])`, 'g'), 'seed=<search>')\n}\n\nfunction orient(delta: number, maximize: boolean): number {\n return maximize ? delta : delta === 0 ? 0 : -delta\n}\n\nfunction orientInterval(interval: [number, number], maximize: boolean): [number, number] {\n return maximize ? interval : [orient(interval[1], false), orient(interval[0], false)]\n}\n\nfunction sortedValues<T>(map: ReadonlyMap<string, T>): T[] {\n return [...map.entries()]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([, value]) => value)\n}\n\nfunction configurationKey(objective: string, genomeDigest: string): string {\n return `${objective}\\u0000${genomeDigest}`\n}\n\nfunction rankValue(value: number | null): number {\n return value === null ? Number.NEGATIVE_INFINITY : value\n}\n\nfunction round(usd: number): number {\n return Math.round(usd * 1e6) / 1e6\n}\n","/**\n * The skill-manifold lens: the node × unit score matrix as candidates in a\n * low-dimensional skill space and units as directions in it.\n *\n * Each observed per-unit mean is modelled as `b_u + P_i · Q_u`: a unit's\n * difficulty `b_u`, the node's coordinates `P_i` and the unit's loading `Q_u`,\n * fitted by alternating ridge least squares over the observed cells only\n * (missing cells are masked, never filled). Scores are standardized first,\n * so coordinates and loadings are unitless. Where every cell scores 0 or 1,\n * the data supports an item-response model instead: a unit's passes on a\n * node are binomial with logit `b_u + P_i · Q_u` (a multidimensional\n * two-parameter logistic model: `Q_u` is the unit's discrimination and `b_u`\n * its easiness), fitted by alternating Newton steps on the penalized\n * likelihood. The rank that generalizes is\n * chosen by cross-validation over held-out cells with the one-standard-error\n * rule (Hastie, Tibshirani and Friedman, Elements of Statistical Learning,\n * §7.10): the intrinsic dimension. Rank 0 means the nodes do not differ\n * beyond noise; rank 1 is one ability axis; more axes mean specialists.\n *\n * The signal is `nextUnit`: the unit whose next cell, run on every leader,\n * removes the largest expected share of the variance of the leaders'\n * contrasts on the whole split (the linear-Gaussian posterior of each\n * leader's coordinates, with unit loadings held fixed). An allocator that\n * extends a rung by this unit needs fewer cells per decision when leaders\n * differ along a skill axis only some units test. Inside one search, a unit\n * only the root has run has no loading, so the lens can also take the\n * loadings of an earlier fit (`calibration`) over the same units: calibrate\n * once, then test adaptively.\n */\n\nimport type { SearchUnitExtension } from '../../campaign/allocation'\nimport type { SearchNodeStatus } from '../../campaign/search-ledger-types'\nimport {\n type SearchScoredCell,\n type SearchStateView,\n searchUnitScores,\n} from '../../campaign/search-state'\nimport { compareCodeUnits, hashCanonical } from '../../ledger-core/canonical'\nimport { cholesky, choleskyInverse, choleskySolve } from '../../math/cholesky'\nimport { symmetricEigen } from '../../math/symmetric-eigen'\nimport { mulberry32 } from '../../statistics/random'\nimport {\n evenSample,\n type GeometryLensResult,\n type GeometrySignal,\n headSequence,\n plural,\n positiveInteger,\n round9,\n} from './geometry'\nimport { INSUFFICIENT_FROM, rankingSplit } from './shared'\n\n// ── Options and output ───────────────────────────────────────────────\n\nexport interface SkillManifoldOptions {\n /** The split scores come from. Default: the ranked split. */\n split?: 'selection' | 'train'\n /** Largest rank the cross-validation tries. Default 4. */\n maxRank?: number\n /** Cross-validation folds over observed cells. Default 5. */\n folds?: number\n /** Leaders the signal separates. Default 3, the claim's finalist cap. */\n leaders?: number\n /** Explicit leaders, for example an allocator's top of a rung. */\n candidates?: readonly string[]\n /** Read only cells settled at or before this ledger sequence, so a caller\n * can re-derive what the lens said at an earlier point of the ledger. */\n asOfSequence?: number\n /** Ridge penalty on standardized coordinates and loadings. Default 1: the\n * maximum a posteriori fit under standard-normal priors on both, since\n * standardized cells have unit variance. Weaker penalties overfit a search\n * of a few nodes (on a real 9-node ledger, 0.1 made the rank-1 held-out\n * error 3.5 times the rank-0 error). */\n ridge?: number\n /** Rows the factor fits and the cross-validation read, evenly spaced in\n * registration order; every row is then placed on the fitted loadings.\n * Default 1000. */\n sampleRows?: number\n /** Unit loadings from an earlier fit over the same units. When given, the\n * lens fits no loadings: it places this search's nodes on them. */\n calibration?: SkillCalibration\n /** `linear` factors standardized per-unit means; `logistic` fits the\n * two-parameter item-response model to pass counts and needs every cell to\n * score 0 or 1. Default `auto`: logistic when every cell scores 0 or 1. */\n model?: 'auto' | 'linear' | 'logistic'\n /** Also choose `count` units greedily from `among` (default: every\n * modelled unit), updating the leaders' posteriors after each pick, so a\n * batch does not repeat one direction. Returned as `data.batch`. */\n batch?: { count: number; among?: readonly string[] }\n}\n\n/** Unit loadings a later search can place its nodes on (`skillCalibration`). */\nexport interface SkillCalibration {\n /** Where the loadings were fitted, for example `searchId@sequence`. */\n source: string\n /** `identity`: the linear model on standardized means; `logit`: the\n * item-response model on pass counts. */\n link: SkillLink\n /** Standardization of the linear model: z = (score − center) / scale; 0\n * and 1 under the logit link. */\n center: number\n scale: number\n rank: number\n ridge: number\n /** Cross-validated squared error of one cell, on the standardized scale;\n * null under the logit link, whose noise is the binomial's. */\n noiseVariance: number | null\n /** Each unit's intercept on the model's scale and its loading. */\n units: Array<{ unitId: string; bias: number; loading: number[] }>\n}\n\nexport type SkillLink = 'identity' | 'logit'\n\nexport interface SkillManifoldNode {\n nodeId: string\n ordinal: number\n status: SearchNodeStatus | null\n /** Units the node scored among the modelled ones. */\n observed: number\n /** Standardized coordinates along each axis; larger is better on axis\n * orientation (see `SkillManifoldData.axes`). */\n coordinates: number[]\n /** The model's mean over every modelled unit, in the metric's units. */\n predictedMean: number\n leader: boolean\n}\n\nexport interface SkillManifoldUnit {\n unitId: string\n /** Nodes that scored the unit (0 for a calibrated unit this search has not run). */\n observedBy: number\n /** The unit's mean for a node at the origin, in the metric's units (a pass\n * rate under the logit link). */\n bias: number\n /** The same intercept on the model's own scale: standardized under the\n * identity link, log-odds under the logit link. */\n intercept: number\n /** The unit's direction in skill space (standardized, or log-odds per\n * unit of coordinate under the logit link). */\n loading: number[]\n /** Length of `loading`: how strongly the unit separates nodes. */\n strength: number\n}\n\nexport interface SkillManifoldNextUnit {\n unitId: string\n /** Expected share of the leaders' contrast variance one more cell on this\n * unit, on every leader, removes; averaged over leader pairs. */\n share: number\n /** Leaders that already scored the unit. */\n measuredBy: number\n}\n\nexport interface SkillManifoldData {\n split: 'selection' | 'train'\n direction: 'maximize' | 'minimize'\n /** `fitted`: loadings fitted on this search; `calibrated`: taken from `source`. */\n mode: 'fitted' | 'calibrated'\n source: string\n matrix: {\n rows: number\n units: number\n /** Observed cells of the modelled matrix (per-unit means). */\n observed: number\n density: number | null\n /** Nodes left out: fewer than 2 modelled units (1 with a calibration). */\n excludedNodes: number\n /** Units left out: scored by fewer than 2 nodes, or absent from the calibration. */\n excludedUnits: number\n fitRows: number\n }\n model: {\n method: string\n link: SkillLink\n rank: number\n ridge: number\n center: number | null\n scale: number | null\n iterations: number\n converged: boolean\n } | null\n /** In-sample R² over rank-0 (unit means only), by rank. */\n explained: {\n byRank: Array<{ rank: number; r2: number }>\n /** Share of the fitted structure each axis carries (its squared singular value). */\n axisShare: number[]\n method: string\n } | null\n intrinsicDimension: {\n value: number | null\n method: string\n /** Held-out cells per rank. */\n n: number\n folds: number\n curve: Array<{ rank: number; error: number; standardError: number }>\n insufficient: string | null\n }\n /** Axis orientation: a positive coordinate is better on the objective. */\n axes: string\n noiseVariance: number | null\n nodes: SkillManifoldNode[]\n units: SkillManifoldUnit[]\n leaders: Array<{ nodeId: string; predictedMean: number; observed: number }>\n nextUnits: SkillManifoldNextUnit[]\n /** The greedy batch `options.batch` asked for; null when not asked or\n * when no unit's information is known. */\n batch: string[] | null\n insufficient: string | null\n}\n\nconst METHODS: Record<\n SkillLink,\n { model: string; intrinsic: string; nextUnit: string; explained: string }\n> = {\n identity: {\n model:\n 'masked matrix factorization: each observed per-unit mean is b_u + P_i·Q_u on standardized scores, fitted by alternating ridge least squares over observed cells only; missing cells are masked, never filled',\n intrinsic:\n 'k-fold cross-validation over observed cells (folds by a hash of node and unit), mean squared error of held-out cells by rank; the intrinsic dimension is the smallest rank within one standard error (across folds) of the best',\n nextUnit:\n 'expected share of the variance of each leader pair’s contrast on the whole split that one more cell on the unit, run on both leaders, removes; each leader’s coordinates have the linear-Gaussian ridge posterior with loadings held fixed and noise equal to the cross-validated cell error; averaged over leader pairs',\n explained:\n 'in-sample R² of each rank over the rank-0 model (unit means only), on the fitted rows; it always grows with rank, which is why the intrinsic dimension is cross-validated',\n },\n logit: {\n model:\n 'multidimensional two-parameter item-response model: a node passes a unit with probability logistic(b_u + P_i·Q_u), its passes on the unit binomial over its cells; fitted by alternating Newton steps on the likelihood with standard-normal priors on P and Q (ridge) and a N(0, 10²) prior on b; missing cells are masked, never filled',\n intrinsic:\n 'k-fold cross-validation over observed node-unit pass counts (folds by a hash of node and unit), binomial log loss per held-out cell by rank; the intrinsic dimension is the smallest rank within one standard error (across folds) of the best',\n nextUnit:\n 'expected share of the variance of each leader pair’s contrast (predicted pass rate on the whole split) that one more cell on the unit, run on both leaders, removes; each leader’s coordinates have the Laplace posterior of the item-response model with loadings held fixed, and a cell’s information is its binomial variance at the leader’s predicted pass rate; averaged over leader pairs',\n explained:\n 'in-sample McFadden pseudo-R² of each rank over the rank-0 model (unit easiness only), on the fitted rows; it always grows with rank, which is why the intrinsic dimension is cross-validated',\n },\n}\n/** The prior precision on a unit's log-odds intercept: N(0, 10²), weak\n * enough to leave any observed pass rate alone and strong enough to keep a\n * unit every node passed (or failed) finite. */\nconst LOGIT_BIAS_PRECISION = 0.01\n/** The largest move one Newton step makes in any coordinate, in log-odds. */\nconst NEWTON_STEP_CAP = 4\n\nconst MAX_ITERATIONS = 300\n/** Relative change of the objective that ends a fit. */\nconst TOLERANCE = 1e-7\n\n// ── The lens ─────────────────────────────────────────────────────────\n\n/**\n * The skill manifold of a search at rank `k` (`auto`: the cross-validated\n * intrinsic dimension, at least 1, and 1 when too few nodes cross-validate).\n * Pure: it reads the state, and `calibration` when given.\n */\nexport function skillManifold(\n state: SearchStateView,\n k: number | 'auto' = 'auto',\n options: SkillManifoldOptions = {},\n): GeometryLensResult<SkillManifoldData> {\n const maxRank = positiveInteger('skillManifold', 'maxRank', options.maxRank ?? 4)\n const folds = positiveInteger('skillManifold', 'folds', options.folds ?? 5)\n if (folds < 2) throw new TypeError(`skillManifold: folds must be at least 2, got ${folds}`)\n const leaderCount = positiveInteger('skillManifold', 'leaders', options.leaders ?? 3)\n const ridge = options.ridge ?? 1\n if (!(ridge > 0) || !Number.isFinite(ridge)) {\n throw new TypeError(`skillManifold: ridge must be a positive number, got ${String(ridge)}`)\n }\n const sampleRows = positiveInteger('skillManifold', 'sampleRows', options.sampleRows ?? 1000)\n if (k !== 'auto') positiveInteger('skillManifold', 'k', k)\n const requested = options.model ?? 'auto'\n if (requested !== 'auto' && requested !== 'linear' && requested !== 'logistic') {\n throw new TypeError(\n `skillManifold: model must be auto, linear or logistic, got ${String(requested)}`,\n )\n }\n\n const header = state.header\n const split = options.split ?? rankingSplit(state)\n const direction = header?.objective.direction ?? 'maximize'\n const sign = direction === 'maximize' ? 1 : -1\n const calibration = options.calibration ?? null\n const source = calibration?.source ?? `${state.searchId}@${headSequence(state)}`\n let link: SkillLink = calibration?.link ?? (requested === 'logistic' ? 'logit' : 'identity')\n const empty = (reason: string, matrix?: SkillManifoldData['matrix']) =>\n result(state, link, {\n split,\n direction,\n mode: calibration ? 'calibrated' : 'fitted',\n source,\n matrix: matrix ?? {\n rows: 0,\n units: 0,\n observed: 0,\n density: null,\n excludedNodes: 0,\n excludedUnits: 0,\n fitRows: 0,\n },\n model: null,\n explained: null,\n intrinsicDimension: {\n value: null,\n method: METHODS[link].intrinsic,\n n: 0,\n folds,\n curve: [],\n insufficient: reason,\n },\n axes: axesNote(direction),\n noiseVariance: null,\n nodes: [],\n units: [],\n leaders: [],\n nextUnits: [],\n batch: null,\n insufficient: reason,\n })\n if (!header || state.rootNodeId === null) {\n return empty(header ? 'the search has no root node yet' : 'the search has not been opened')\n }\n\n const matrix = scoreMatrix(state, split, options.asOfSequence, calibration)\n const shape: SkillManifoldData['matrix'] = {\n rows: matrix.rows.length,\n units: matrix.unitIds.length,\n observed: matrix.observed,\n density:\n matrix.rows.length * matrix.unitIds.length > 0\n ? round9(matrix.observed / (matrix.rows.length * matrix.unitIds.length))\n : null,\n excludedNodes: matrix.excludedNodes,\n excludedUnits: matrix.excludedUnits,\n fitRows: 0,\n }\n if (!calibration) {\n if (requested === 'logistic' && !matrix.binary) {\n throw new TypeError(\n 'skillManifold: model logistic needs every modelled cell to score 0 or 1; use auto or linear',\n )\n }\n link = requested === 'linear' || !matrix.binary ? 'identity' : 'logit'\n } else if (link === 'logit' && !matrix.binary) {\n return empty(\n `the calibration from ${calibration.source} is an item-response model, and this search has cells that score other than 0 or 1`,\n shape,\n )\n }\n\n let center: number\n let scale: number\n let fit: Fit\n let rank: number\n let noiseVariance: number | null\n let intrinsic: SkillManifoldData['intrinsicDimension']\n let explained: SkillManifoldData['explained'] = null\n let iterations = 0\n let converged = true\n\n if (calibration) {\n if (matrix.rows.length === 0 || matrix.unitIds.length === 0) {\n return empty('no node scored a calibrated unit', shape)\n }\n center = calibration.center\n scale = calibration.scale\n rank = calibration.rank\n const byUnit = new Map(calibration.units.map((unit) => [unit.unitId, unit]))\n fit = {\n rank,\n bias: matrix.unitIds.map((unitId) => byUnit.get(unitId)!.bias),\n loadings: matrix.unitIds.map((unitId) => [...byUnit.get(unitId)!.loading]),\n byRow: new Map(),\n coordinates: [],\n iterations: 0,\n converged: true,\n }\n placeRows(matrix, fit, center, scale, calibration.ridge, link)\n noiseVariance = calibration.noiseVariance\n intrinsic = {\n value: null,\n method: METHODS[link].intrinsic,\n n: 0,\n folds,\n curve: [],\n insufficient: `loadings come from ${calibration.source}; its fit decided the rank (${rank})`,\n }\n } else {\n if (matrix.rows.length < 3 || matrix.unitIds.length < INSUFFICIENT_FROM) {\n return empty(\n `${plural(matrix.rows.length, 'node')} and ${plural(matrix.unitIds.length, 'unit')} qualify (a unit counts when 2 or more nodes scored it, a node when it scored 2 or more such units); a manifold needs 3 nodes and ${INSUFFICIENT_FROM} units`,\n shape,\n )\n }\n const standard = standardization(matrix)\n if (standard === null) {\n return empty(\n 'every node scores the same on every unit, so there is no variation to factor',\n shape,\n )\n }\n ;({ center, scale } = link === 'logit' ? { center: 0, scale: 1 } : standard)\n const fitRows = evenSample(\n matrix.rows.map((_, index) => index),\n sampleRows,\n )\n shape.fitRows = fitRows.length\n const cells = observedCells(matrix, fitRows, center, scale)\n const rankCap = Math.min(maxRank, matrix.unitIds.length - 1, fitRows.length - 1)\n intrinsic = crossValidate(matrix, cells, rankCap, folds, ridge, link)\n // Under 'auto' without a cross-validated dimension, fit one axis only: a\n // second axis on a handful of nodes fits their noise, and its in-sample\n // R² would read as structure.\n rank = k === 'auto' ? Math.max(1, intrinsic.value ?? 1) : Math.min(k, Math.max(1, rankCap))\n const fits: Fit[] = []\n for (let r = 0; r <= Math.max(rank, rankCap); r++) {\n fits.push(factor(matrix.unitIds.length, cells, r, ridge, link))\n }\n const base = loss(fits[0]!, cells, link)\n explained = {\n byRank: fits.slice(1).map((entry) => ({\n rank: entry.rank,\n r2: round9(base > 0 ? 1 - loss(entry, cells, link) / base : 0),\n })),\n axisShare: [],\n method: METHODS[link].explained,\n }\n fit = fits[rank]!\n iterations = fit.iterations\n converged = fit.converged\n const cv = intrinsic.curve.find((point) => point.rank === rank)\n noiseVariance = link === 'identity' && cv && Number.isFinite(cv.error) ? cv.error : null\n const shares = principalAxes(fit, fitRows)\n explained.axisShare = shares.map(round9)\n fit.coordinates = []\n placeRows(matrix, fit, center, scale, ridge, link)\n }\n orientAxes(fit, sign)\n\n const unitCount = matrix.unitIds.length\n const meanLoading = new Array<number>(rank).fill(0)\n for (const loading of fit.loadings) {\n for (let d = 0; d < rank; d++) meanLoading[d]! += loading[d]! / unitCount\n }\n const meanBias = fit.bias.reduce((sum, value) => sum + value, 0) / unitCount\n const predicted = (coordinates: readonly number[]): number => {\n if (link === 'identity') return center + scale * (meanBias + dot(coordinates, meanLoading))\n let total = 0\n for (let u = 0; u < unitCount; u++) {\n total += logistic(fit.bias[u]! + dot(coordinates, fit.loadings[u]!))\n }\n return total / unitCount\n }\n\n const leaderFloor = Math.min(INSUFFICIENT_FROM, unitCount)\n let leaderRows: number[]\n if (options.candidates) {\n const wanted = new Set(options.candidates)\n leaderRows = matrix.rows.flatMap((row, index) => (wanted.has(row.nodeId) ? [index] : []))\n } else {\n // A node decided invalid (a judge integrity or admission failure) never\n // leads: its score may be a reward hack, and cells spent separating it\n // from the real leaders would be wasted (§6.6).\n const eligible = matrix.rows\n .map((row, index) => ({ row, index }))\n .filter(({ row }) => row.observed.size >= leaderFloor && row.status !== 'invalid')\n leaderRows = eligible\n .sort(\n (left, right) =>\n sign *\n (predicted(fit.coordinates[right.index]!) - predicted(fit.coordinates[left.index]!)) ||\n left.row.ordinal - right.row.ordinal,\n )\n .slice(0, leaderCount)\n .map(({ index }) => index)\n }\n const leaderSet = new Set(leaderRows)\n\n const next =\n intrinsic.value === 0\n ? {\n ranked: [],\n batch: null,\n insufficient:\n 'held-out cells fit no better with any skill axis than with unit means alone (intrinsic dimension 0): the nodes do not differ beyond noise, so no unit separates them',\n }\n : !calibration && intrinsic.value === null\n ? {\n ranked: [],\n batch: null,\n insufficient:\n 'the skill axes are not cross-validated (see the intrinsic dimension), so no unit’s information is known',\n }\n : nextUnits(\n matrix,\n fit,\n leaderRows,\n noiseVariance,\n calibration?.ridge ?? ridge,\n options.batch ?? null,\n link,\n )\n const nodes: SkillManifoldNode[] = matrix.rows.map((row, index) => ({\n nodeId: row.nodeId,\n ordinal: row.ordinal,\n status: row.status,\n observed: row.observed.size,\n coordinates: fit.coordinates[index]!.map(round9),\n predictedMean: round9(predicted(fit.coordinates[index]!)),\n leader: leaderSet.has(index),\n }))\n const units: SkillManifoldUnit[] = matrix.unitIds.map((unitId, u) => ({\n unitId,\n observedBy: matrix.observedBy[u]!,\n bias: round9(link === 'identity' ? center + scale * fit.bias[u]! : logistic(fit.bias[u]!)),\n intercept: round9(fit.bias[u]!),\n loading: fit.loadings[u]!.map(round9),\n strength: round9(Math.hypot(...fit.loadings[u]!)),\n }))\n\n return result(state, link, {\n split,\n direction,\n mode: calibration ? 'calibrated' : 'fitted',\n source,\n matrix: shape,\n model: {\n method: METHODS[link].model,\n link,\n rank,\n ridge: calibration?.ridge ?? ridge,\n center: round9(center),\n scale: round9(scale),\n iterations,\n converged,\n },\n explained,\n intrinsicDimension: intrinsic,\n axes: axesNote(direction),\n noiseVariance: noiseVariance === null ? null : round9(noiseVariance),\n nodes,\n units,\n leaders: leaderRows.map((index) => ({\n nodeId: matrix.rows[index]!.nodeId,\n predictedMean: round9(predicted(fit.coordinates[index]!)),\n observed: matrix.rows[index]!.observed.size,\n })),\n nextUnits: next.ranked,\n batch: options.batch ? next.batch : null,\n insufficient: next.insufficient,\n })\n}\n\n/** The loadings of a fitted manifold, for a later search over the same units\n * to place its nodes on. Null unless cross-validation found at least one skill\n * axis (intrinsic dimension 1 or more), and, for the linear model, measured\n * the cell noise: loadings of an axis the held-out cells do not support would\n * steer allocation by noise. */\nexport function skillCalibration(\n lens: GeometryLensResult<SkillManifoldData>,\n): SkillCalibration | null {\n const { data } = lens\n const { model } = data\n if (\n data.mode !== 'fitted' ||\n model === null ||\n model.center === null ||\n model.scale === null ||\n (model.link === 'identity' && data.noiseVariance === null) ||\n data.intrinsicDimension.value === null ||\n data.intrinsicDimension.value < 1\n ) {\n return null\n }\n return {\n source: data.source,\n link: model.link,\n center: model.center,\n scale: model.scale,\n rank: model.rank,\n ridge: model.ridge,\n noiseVariance: data.noiseVariance,\n units: data.units.map((unit) => ({\n unitId: unit.unitId,\n bias: unit.intercept,\n loading: [...unit.loading],\n })),\n }\n}\n\nfunction result(\n state: SearchStateView,\n link: SkillLink,\n data: SkillManifoldData,\n): GeometryLensResult<SkillManifoldData> {\n const pending = data.nextUnits.filter((unit) => unit.measuredBy < data.leaders.length)\n const best = pending[0] ?? data.nextUnits[0] ?? null\n const signal: GeometrySignal = {\n name: 'nextUnit',\n value: best === null ? null : best.share,\n subject: best?.unitId ?? null,\n method: METHODS[link].nextUnit,\n n: data.leaders.reduce((sum, leader) => sum + leader.observed, 0),\n insufficient: best === null ? (data.insufficient ?? 'no unit to rank') : null,\n }\n return {\n lens: 'skillManifold',\n searchId: state.searchId,\n sequence: headSequence(state),\n data,\n signal,\n }\n}\n\nfunction axesNote(direction: 'maximize' | 'minimize'): string {\n return direction === 'maximize'\n ? 'axes are principal (largest share first) and oriented so the mean unit loads positively: a larger coordinate predicts a higher score'\n : 'axes are principal (largest share first) and oriented so the mean unit loads negatively: a larger coordinate predicts a lower (better) score'\n}\n\n// ── The matrix ───────────────────────────────────────────────────────\n\ninterface Row {\n nodeId: string\n ordinal: number\n status: SearchNodeStatus | null\n /** Modelled unit index → per-unit mean. */\n observed: Map<number, number>\n /** Modelled unit index → the unit's summed score and scored cells: passes\n * and trials when every cell scores 0 or 1. */\n counts: Map<number, { sum: number; count: number }>\n}\n\ninterface ScoreMatrix {\n rows: Row[]\n unitIds: string[]\n observedBy: number[]\n observed: number\n excludedNodes: number\n excludedUnits: number\n /** Every scored cell of the modelled rows scores exactly 0 or 1. */\n binary: boolean\n}\n\n/**\n * Per-unit means of every node on `split`. Without a calibration, a unit is\n * modelled when 2 or more nodes scored it and a node when it scored 2 or more\n * modelled units, repeated until both hold. With one, the modelled units are\n * the calibration's, and a node needs one of them.\n */\nfunction scoreMatrix(\n state: SearchStateView,\n split: 'selection' | 'train',\n asOf: number | undefined,\n calibration: SkillCalibration | null,\n): ScoreMatrix {\n const raw: Array<{\n nodeId: string\n ordinal: number\n status: SearchNodeStatus | null\n units: Map<string, number>\n counts: Map<string, { sum: number; count: number }>\n binary: boolean\n }> = []\n const allUnits = new Set<string>()\n for (const node of state.nodes()) {\n const cells =\n asOf === undefined\n ? state.scoredCells(node.nodeId, split)\n : scoredAsOf(state, node.nodeId, split, asOf)\n const scores = searchUnitScores(cells)\n const units = new Map(scores.map((unit) => [unit.unitId, unit.mean]))\n const counts = new Map(\n scores.map((unit) => [unit.unitId, { sum: unit.sum, count: unit.count }]),\n )\n for (const unitId of units.keys()) allUnits.add(unitId)\n raw.push({\n nodeId: node.nodeId,\n ordinal: node.ordinal,\n status: node.status,\n units,\n counts,\n binary: cells.every((cell) => cell.score === 0 || cell.score === 1),\n })\n }\n let unitIds: string[]\n let keep: typeof raw\n if (calibration) {\n const calibrated = new Set(calibration.units.map((unit) => unit.unitId))\n unitIds = calibration.units.map((unit) => unit.unitId)\n keep = raw.filter((row) => [...row.units.keys()].some((unitId) => calibrated.has(unitId)))\n } else {\n let units = new Set(allUnits)\n keep = raw\n for (;;) {\n const counts = new Map<string, number>()\n for (const row of keep) {\n for (const unitId of row.units.keys()) {\n if (units.has(unitId)) counts.set(unitId, (counts.get(unitId) ?? 0) + 1)\n }\n }\n const nextUnits = new Set([...units].filter((unitId) => (counts.get(unitId) ?? 0) >= 2))\n const nextKeep = keep.filter(\n (row) => [...row.units.keys()].filter((unitId) => nextUnits.has(unitId)).length >= 2,\n )\n const stable = nextUnits.size === units.size && nextKeep.length === keep.length\n units = nextUnits\n keep = nextKeep\n if (stable) break\n }\n unitIds = [...units].sort(compareCodeUnits)\n }\n const unitIndex = new Map(unitIds.map((unitId, index) => [unitId, index]))\n const observedBy = new Array<number>(unitIds.length).fill(0)\n let observed = 0\n const rows = keep.map((row) => {\n const map = new Map<number, number>()\n const counts = new Map<number, { sum: number; count: number }>()\n for (const [unitId, mean] of row.units) {\n const index = unitIndex.get(unitId)\n if (index === undefined) continue\n map.set(index, mean)\n counts.set(index, row.counts.get(unitId)!)\n observedBy[index]! += 1\n observed += 1\n }\n return { nodeId: row.nodeId, ordinal: row.ordinal, status: row.status, observed: map, counts }\n })\n return {\n rows,\n unitIds,\n observedBy,\n observed,\n binary: keep.length > 0 && keep.every((row) => row.binary),\n excludedNodes: raw.length - rows.length,\n excludedUnits: calibration\n ? [...allUnits].filter((unitId) => !unitIndex.has(unitId)).length\n : allUnits.size - unitIds.length,\n }\n}\n\n/** A node's scored cells on `split` whose score the ledger held at `asOf`:\n * a cell's last update is its scoring settle, so a later retry is excluded. */\nfunction scoredAsOf(\n state: SearchStateView,\n nodeId: string,\n split: 'selection' | 'train',\n asOf: number,\n): SearchScoredCell[] {\n const cells: SearchScoredCell[] = []\n for (const cell of state.cells({ nodeId })) {\n if (cell.split !== split || cell.score === null || cell.updatedSequence > asOf) continue\n cells.push({\n cellId: cell.cellId,\n unitId: cell.unitId,\n attempt: cell.attempts,\n score: cell.score,\n })\n }\n return cells\n}\n\nfunction standardization(matrix: ScoreMatrix): { center: number; scale: number } | null {\n let total = 0\n const columnSum = new Array<number>(matrix.unitIds.length).fill(0)\n for (const row of matrix.rows) {\n for (const [u, value] of row.observed) {\n total += value\n columnSum[u]! += value\n }\n }\n const center = total / matrix.observed\n let squares = 0\n for (const row of matrix.rows) {\n for (const [u, value] of row.observed) {\n squares += (value - columnSum[u]! / matrix.observedBy[u]!) ** 2\n }\n }\n const scale = Math.sqrt(squares / matrix.observed)\n return scale > 1e-12 ? { center, scale } : null\n}\n\ninterface Cell {\n row: number\n unit: number\n /** The standardized per-unit mean (identity link). */\n z: number\n /** Passes and trials (logit link): the unit's summed score and its cells. */\n k: number\n n: number\n fold: number\n}\n\nfunction observedCells(\n matrix: ScoreMatrix,\n rows: readonly number[],\n center: number,\n scale: number,\n): Cell[] {\n const cells: Cell[] = []\n for (const row of rows) {\n const { nodeId, observed, counts } = matrix.rows[row]!\n for (const [unit, value] of [...observed].sort(([left], [right]) => left - right)) {\n const { sum, count } = counts.get(unit)!\n cells.push({\n row,\n unit,\n z: (value - center) / scale,\n k: sum,\n n: count,\n fold: fnv1a(`${nodeId}\\u0000${matrix.unitIds[unit]!}`),\n })\n }\n }\n return cells\n}\n\n/** 32-bit FNV-1a: a deterministic fold assignment that depends on the cell's\n * coordinates alone, not on the order cells were read. */\nfunction fnv1a(text: string): number {\n let hash = 0x811c9dc5\n for (let index = 0; index < text.length; index++) {\n hash ^= text.charCodeAt(index)\n hash = Math.imul(hash, 0x01000193)\n }\n return hash >>> 0\n}\n\n// ── The factorization ────────────────────────────────────────────────\n\ninterface Fit {\n rank: number\n /** Per modelled unit, standardized. */\n bias: number[]\n loadings: number[][]\n /** Coordinates of the rows the fit read, by matrix row index. */\n byRow: Map<number, number[]>\n /** Coordinates of every matrix row, once `placeRows` ran. */\n coordinates: number[][]\n iterations: number\n converged: boolean\n}\n\n/** The fit of `rank` axes under `link`. */\nfunction factor(\n units: number,\n cells: readonly Cell[],\n rank: number,\n ridge: number,\n link: SkillLink,\n): Fit {\n return link === 'identity'\n ? factorLinear(units, cells, rank, ridge)\n : factorLogistic(units, cells, rank, ridge)\n}\n\nfunction groupCells(\n units: number,\n cells: readonly Cell[],\n): { byUnit: Cell[][]; byRow: Map<number, Cell[]> } {\n const byUnit: Cell[][] = Array.from({ length: units }, () => [])\n const byRow = new Map<number, Cell[]>()\n for (const cell of cells) {\n byUnit[cell.unit]!.push(cell)\n const list = byRow.get(cell.row)\n if (list) list.push(cell)\n else byRow.set(cell.row, [cell])\n }\n return { byUnit, byRow }\n}\n\n/** Loadings start from a fixed seeded draw, so a fit is deterministic. */\nfunction seededLoadings(units: number, rank: number): number[][] {\n const random = mulberry32(0x5eed + rank)\n return Array.from({ length: units }, () =>\n Array.from({ length: rank }, () => (random() - 0.5) * 0.2),\n )\n}\n\n/**\n * Alternating ridge least squares over `cells`: rows' coordinates given the\n * loadings, then each unit's loading and (unpenalized) bias given the\n * coordinates, until the objective moves by less than 1e-7 of itself.\n */\nfunction factorLinear(units: number, cells: readonly Cell[], rank: number, ridge: number): Fit {\n const { byUnit, byRow: rowIds } = groupCells(units, cells)\n const bias = byUnit.map((list) =>\n list.length === 0 ? 0 : list.reduce((sum, cell) => sum + cell.z, 0) / list.length,\n )\n const loadings = seededLoadings(units, rank)\n const coordinates = new Map<number, number[]>()\n for (const row of rowIds.keys()) coordinates.set(row, new Array<number>(rank).fill(0))\n if (rank === 0) {\n return {\n rank,\n bias,\n loadings,\n byRow: coordinates,\n coordinates: [],\n iterations: 0,\n converged: true,\n }\n }\n let previous = Number.POSITIVE_INFINITY\n let iterations = 0\n let converged = false\n for (; iterations < MAX_ITERATIONS; iterations++) {\n for (const [row, list] of rowIds) {\n coordinates.set(row, solveRow(list, loadings, bias, rank, ridge, 'identity'))\n }\n for (let u = 0; u < units; u++) {\n const list = byUnit[u]!\n if (list.length === 0) continue\n const size = rank + 1\n const system = Array.from({ length: size }, (_, i) =>\n Array.from({ length: size }, (_, j) => (i === j && i < rank ? ridge : 0)),\n )\n const rhs = new Array<number>(size).fill(0)\n for (const cell of list) {\n const point = coordinates.get(cell.row)!\n for (let i = 0; i < size; i++) {\n const xi = i < rank ? point[i]! : 1\n rhs[i]! += xi * cell.z\n const line = system[i]!\n for (let j = 0; j < size; j++) line[j]! += xi * (j < rank ? point[j]! : 1)\n }\n }\n const lower = cholesky(system)\n if (lower === null) continue\n const solution = choleskySolve(lower, rhs)\n loadings[u] = solution.slice(0, rank)\n bias[u] = solution[rank]!\n }\n let objective = 0\n for (const cell of cells) {\n objective +=\n (cell.z - bias[cell.unit]! - dot(coordinates.get(cell.row)!, loadings[cell.unit]!)) ** 2\n }\n for (const point of coordinates.values()) objective += ridge * dot(point, point)\n for (const loading of loadings) objective += ridge * dot(loading, loading)\n if (Math.abs(previous - objective) <= TOLERANCE * Math.max(objective, 1e-12)) {\n converged = true\n iterations += 1\n break\n }\n previous = objective\n }\n return { rank, bias, loadings, byRow: coordinates, coordinates: [], iterations, converged }\n}\n\n/**\n * The item-response fit: alternating Newton steps on the penalized binomial\n * likelihood, each row's coordinates given the loadings, then each unit's\n * loading and intercept given the coordinates, until the objective moves by\n * less than 1e-7 of itself. Priors: standard normal on coordinates and\n * loadings (scaled by `ridge`), N(0, 10²) on each intercept, which keeps a\n * unit every node passed finite. A step moves no parameter by more than 4.\n */\nfunction factorLogistic(units: number, cells: readonly Cell[], rank: number, ridge: number): Fit {\n const { byUnit, byRow: rowIds } = groupCells(units, cells)\n const bias = byUnit.map((list) => {\n let k = 0\n let n = 0\n for (const cell of list) {\n k += cell.k\n n += cell.n\n }\n return Math.log((k + 0.5) / (n - k + 0.5))\n })\n const loadings = seededLoadings(units, rank)\n const coordinates = new Map<number, number[]>()\n for (const row of rowIds.keys()) coordinates.set(row, new Array<number>(rank).fill(0))\n const objectiveOf = (): number => {\n let total = 0\n for (const cell of cells) {\n total += binomialLoss(\n cell,\n bias[cell.unit]! + dot(coordinates.get(cell.row)!, loadings[cell.unit]!),\n )\n }\n for (const point of coordinates.values()) total += (ridge / 2) * dot(point, point)\n for (const loading of loadings) total += (ridge / 2) * dot(loading, loading)\n for (const value of bias) total += (LOGIT_BIAS_PRECISION / 2) * value * value\n return total\n }\n let previous = Number.POSITIVE_INFINITY\n let iterations = 0\n let converged = false\n for (; iterations < MAX_ITERATIONS; iterations++) {\n if (rank > 0) {\n for (const [row, list] of rowIds) {\n const point = coordinates.get(row)!\n coordinates.set(row, newtonStep(point, list, loadings, bias, ridge))\n }\n }\n for (let u = 0; u < units; u++) {\n const list = byUnit[u]!\n if (list.length === 0) continue\n const size = rank + 1\n const theta = [...loadings[u]!, bias[u]!]\n const precision = (i: number): number => (i < rank ? ridge : LOGIT_BIAS_PRECISION)\n const hessian = Array.from({ length: size }, (_, i) =>\n Array.from({ length: size }, (_, j) => (i === j ? precision(i) : 0)),\n )\n const gradient = theta.map((value, i) => -precision(i) * value)\n for (const cell of list) {\n const point = coordinates.get(cell.row)!\n const p = logistic(theta[rank]! + dot(point, theta))\n const weight = cell.n * p * (1 - p)\n for (let i = 0; i < size; i++) {\n const xi = i < rank ? point[i]! : 1\n gradient[i]! += (cell.k - cell.n * p) * xi\n const line = hessian[i]!\n for (let j = 0; j < size; j++) line[j]! += weight * xi * (j < rank ? point[j]! : 1)\n }\n }\n const lower = cholesky(hessian)\n if (lower === null) continue\n const step = capped(choleskySolve(lower, gradient))\n loadings[u] = theta.slice(0, rank).map((value, i) => value + step[i]!)\n bias[u] = theta[rank]! + step[rank]!\n }\n const objective = objectiveOf()\n if (Math.abs(previous - objective) <= TOLERANCE * Math.max(objective, 1e-12)) {\n converged = true\n iterations += 1\n break\n }\n previous = objective\n }\n return { rank, bias, loadings, byRow: coordinates, coordinates: [], iterations, converged }\n}\n\n/** One Newton step on a row's coordinates under the item-response model. */\nfunction newtonStep(\n point: readonly number[],\n list: readonly Pick<Cell, 'unit' | 'k' | 'n'>[],\n loadings: readonly (readonly number[])[],\n bias: readonly number[],\n ridge: number,\n): number[] {\n const rank = point.length\n const hessian = Array.from({ length: rank }, (_, i) =>\n Array.from({ length: rank }, (_, j) => (i === j ? ridge : 0)),\n )\n const gradient = point.map((value) => -ridge * value)\n for (const cell of list) {\n const q = loadings[cell.unit]!\n const p = logistic(bias[cell.unit]! + dot(point, q))\n const weight = cell.n * p * (1 - p)\n for (let i = 0; i < rank; i++) {\n gradient[i]! += (cell.k - cell.n * p) * q[i]!\n for (let j = 0; j < rank; j++) hessian[i]![j]! += weight * q[i]! * q[j]!\n }\n }\n const step = capped(choleskySolve(cholesky(hessian)!, gradient))\n return point.map((value, i) => value + step[i]!)\n}\n\nfunction capped(step: readonly number[]): number[] {\n const largest = Math.max(0, ...step.map(Math.abs))\n return largest > NEWTON_STEP_CAP\n ? step.map((value) => (value * NEWTON_STEP_CAP) / largest)\n : [...step]\n}\n\n/** −log of the binomial likelihood of `k` passes in `n` at log-odds `eta`,\n * without the binomial coefficient: n·log(1 + e^η) − k·η, computed stably. */\nfunction binomialLoss(cell: Pick<Cell, 'k' | 'n'>, eta: number): number {\n const softplus = Math.max(eta, 0) + Math.log1p(Math.exp(-Math.abs(eta)))\n return cell.n * softplus - cell.k * eta\n}\n\nfunction logistic(eta: number): number {\n if (eta >= 0) return 1 / (1 + Math.exp(-eta))\n const e = Math.exp(eta)\n return e / (1 + e)\n}\n\n/** A row's coordinates given the loadings: one ridge solve (identity), or\n * Newton steps to convergence (logit). */\nfunction solveRow(\n list: readonly Pick<Cell, 'unit' | 'z' | 'k' | 'n'>[],\n loadings: readonly (readonly number[])[],\n bias: readonly number[],\n rank: number,\n ridge: number,\n link: SkillLink,\n): number[] {\n if (link === 'logit') {\n let point = new Array<number>(rank).fill(0)\n for (let iteration = 0; iteration < 50; iteration++) {\n const next = newtonStep(point, list, loadings, bias, ridge)\n const moved = Math.max(0, ...next.map((value, i) => Math.abs(value - point[i]!)))\n point = next\n if (moved < 1e-10) break\n }\n return point\n }\n const system = Array.from({ length: rank }, (_, i) =>\n Array.from({ length: rank }, (_, j) => (i === j ? ridge : 0)),\n )\n const rhs = new Array<number>(rank).fill(0)\n for (const cell of list) {\n const q = loadings[cell.unit]!\n const residual = cell.z - bias[cell.unit]!\n for (let i = 0; i < rank; i++) {\n rhs[i]! += q[i]! * residual\n for (let j = 0; j < rank; j++) system[i]![j]! += q[i]! * q[j]!\n }\n }\n return choleskySolve(cholesky(system)!, rhs)\n}\n\n/** The model's linear predictor: standardized mean (identity) or log-odds (logit). */\nfunction predict(fit: Fit, point: readonly number[] | undefined, unit: number): number {\n return fit.bias[unit]! + (point ? dot(point, fit.loadings[unit]!) : 0)\n}\n\n/** Squared error (identity) or binomial log loss (logit) of the fit on `cells`. */\nfunction loss(fit: Fit, cells: readonly Cell[], link: SkillLink): number {\n let total = 0\n for (const cell of cells)\n total += cellLoss(cell, predict(fit, fit.byRow.get(cell.row), cell.unit), link)\n return total\n}\n\nfunction cellLoss(cell: Cell, eta: number, link: SkillLink): number {\n return link === 'identity' ? (cell.z - eta) ** 2 : binomialLoss(cell, eta)\n}\n\n/** Every matrix row placed on the fitted loadings. */\nfunction placeRows(\n matrix: ScoreMatrix,\n fit: Fit,\n center: number,\n scale: number,\n ridge: number,\n link: SkillLink,\n): void {\n fit.coordinates = matrix.rows.map((row) => {\n if (fit.rank === 0) return []\n const list = [...row.observed].map(([unit, value]) => ({\n unit,\n z: (value - center) / scale,\n k: row.counts.get(unit)!.sum,\n n: row.counts.get(unit)!.count,\n }))\n return solveRow(list, fit.loadings, fit.bias, fit.rank, ridge, link)\n })\n}\n\n/**\n * Rotates the fitted rows and loadings to principal axes: the singular\n * vectors of the fitted low-rank matrix, largest first, with the scale split\n * evenly between rows and loadings. The product the model predicts is\n * unchanged. Returns each axis's share of the squared singular values.\n */\nfunction principalAxes(fit: Fit, fitRows: readonly number[]): number[] {\n const rank = fit.rank\n const byRow = fit.byRow\n const rows = fitRows.map((row) => byRow.get(row) ?? new Array<number>(rank).fill(0))\n const gram = (vectors: readonly (readonly number[])[]) =>\n Array.from({ length: rank }, (_, i) =>\n Array.from({ length: rank }, (_, j) => vectors.reduce((sum, v) => sum + v[i]! * v[j]!, 0)),\n )\n const lowerP = cholesky(gram(rows))\n const lowerQ = cholesky(gram(fit.loadings))\n if (lowerP === null || lowerQ === null) return []\n // C = Lpᵀ Lq; its SVD A Σ Bᵀ comes from the eigenvectors B of CᵀC.\n const c = Array.from({ length: rank }, (_, i) =>\n Array.from({ length: rank }, (_, j) => {\n let sum = 0\n for (let m = 0; m < rank; m++) sum += lowerP[m]![i]! * lowerQ[m]![j]!\n return sum\n }),\n )\n const ctc = Array.from({ length: rank }, (_, i) =>\n Array.from({ length: rank }, (_, j) => {\n let sum = 0\n for (let m = 0; m < rank; m++) sum += c[m]![i]! * c[m]![j]!\n return sum\n }),\n )\n const { values, vectors } = symmetricEigen(ctc)\n const sigma = values.map((value) => Math.sqrt(Math.max(value, 0)))\n if (sigma.some((value) => value <= 1e-12)) return []\n // B has eigenvectors as columns; A = C B Σ⁻¹.\n const b = Array.from({ length: rank }, (_, i) => vectors.map((vector) => vector[i]!))\n const a = Array.from({ length: rank }, (_, i) =>\n Array.from({ length: rank }, (_, j) => {\n let sum = 0\n for (let m = 0; m < rank; m++) sum += c[i]![m]! * b[m]![j]!\n return sum / sigma[j]!\n }),\n )\n const upperInverse = (lower: number[][]) => transpose(lowerInverse(lower))\n const transformP = multiply(multiply(upperInverse(lowerP), a), diagonal(sigma.map(Math.sqrt)))\n const transformQ = multiply(multiply(upperInverse(lowerQ), b), diagonal(sigma.map(Math.sqrt)))\n for (const [row, point] of byRow) byRow.set(row, applyRow(point, transformP))\n fit.loadings = fit.loadings.map((loading) => applyRow(loading, transformQ))\n const total = values.reduce((sum, value) => sum + Math.max(value, 0), 0)\n return values.map((value) => Math.max(value, 0) / total)\n}\n\n/** Flips each axis so the mean loading points toward a better score. */\nfunction orientAxes(fit: Fit, sign: number): void {\n for (let d = 0; d < fit.rank; d++) {\n let mean = 0\n for (const loading of fit.loadings) mean += loading[d]!\n if (sign * mean >= 0) continue\n for (const loading of fit.loadings) loading[d] = -loading[d]! || 0\n for (const point of fit.coordinates) point[d] = -point[d]! || 0\n for (const point of fit.byRow.values()) point[d] = -point[d]! || 0\n }\n}\n\n// ── Cross-validation ─────────────────────────────────────────────────\n\nfunction crossValidate(\n matrix: ScoreMatrix,\n cells: readonly Cell[],\n rankCap: number,\n folds: number,\n ridge: number,\n link: SkillLink,\n): SkillManifoldData['intrinsicDimension'] {\n const rows = new Set(cells.map((cell) => cell.row)).size\n if (rows < INSUFFICIENT_FROM || matrix.unitIds.length < INSUFFICIENT_FROM) {\n return {\n value: null,\n method: METHODS[link].intrinsic,\n n: 0,\n folds,\n curve: [],\n insufficient: `cross-validation needs ${INSUFFICIENT_FROM} nodes and ${INSUFFICIENT_FROM} units; ${plural(rows, 'node')} and ${plural(matrix.unitIds.length, 'unit')} qualify`,\n }\n }\n const curve: Array<{ rank: number; error: number; standardError: number }> = []\n let held = 0\n for (let rank = 0; rank <= rankCap; rank++) {\n const foldErrors: number[] = []\n let squares = 0\n let count = 0\n for (let fold = 0; fold < folds; fold++) {\n const train = cells.filter((cell) => cell.fold % folds !== fold)\n const test = cells.filter((cell) => cell.fold % folds === fold)\n const fit = factor(matrix.unitIds.length, train, rank, ridge, link)\n const trained = new Set(train.map((cell) => cell.unit))\n let foldSquares = 0\n let foldCount = 0\n for (const cell of test) {\n if (!trained.has(cell.unit)) continue\n foldSquares += cellLoss(cell, predict(fit, fit.byRow.get(cell.row), cell.unit), link)\n foldCount += 1\n }\n if (foldCount > 0) foldErrors.push(foldSquares / foldCount)\n squares += foldSquares\n count += foldCount\n }\n held = count\n const error = count > 0 ? squares / count : Number.NaN\n const spread =\n foldErrors.length > 1\n ? Math.sqrt(\n foldErrors.reduce((sum, value) => sum + (value - mean(foldErrors)) ** 2, 0) /\n (foldErrors.length - 1) /\n foldErrors.length,\n )\n : Number.NaN\n curve.push({ rank, error: round9(error), standardError: round9(spread) })\n }\n const finite = curve.filter((point) => Number.isFinite(point.error))\n if (finite.length === 0) {\n return {\n value: null,\n method: METHODS[link].intrinsic,\n n: held,\n folds,\n curve,\n insufficient: 'no held-out cell had a unit the rest of the data measured',\n }\n }\n const best = finite.reduce((left, right) => (right.error < left.error ? right : left))\n const bar = best.error + (Number.isFinite(best.standardError) ? best.standardError : 0)\n const chosen = finite.find((point) => point.error <= bar)!\n return {\n value: chosen.rank,\n method: METHODS[link].intrinsic,\n n: held,\n folds,\n curve,\n insufficient: null,\n }\n}\n\n// ── The next unit ────────────────────────────────────────────────────\n\nfunction nextUnits(\n matrix: ScoreMatrix,\n fit: Fit,\n leaderRows: readonly number[],\n noiseVariance: number | null,\n ridge: number,\n batch: { count: number; among?: readonly string[] } | null,\n link: SkillLink,\n): { ranked: SkillManifoldNextUnit[]; batch: string[] | null; insufficient: string | null } {\n if (leaderRows.length < 2) {\n return {\n ranked: [],\n batch: null,\n insufficient: `${plural(leaderRows.length, 'leader')} qualify (${INSUFFICIENT_FROM} or more modelled units); separating leaders needs 2`,\n }\n }\n if (link === 'identity' && (noiseVariance === null || !(noiseVariance > 0))) {\n return {\n ranked: [],\n batch: null,\n insufficient: 'the cell noise is unmeasured, so no unit’s information is known',\n }\n }\n if (fit.rank === 0) {\n return { ranked: [], batch: null, insufficient: 'rank 0: the nodes do not differ beyond noise' }\n }\n const rank = fit.rank\n const units = matrix.unitIds.length\n // Per leader: the noise of one more cell on each unit, the posterior\n // covariance of its coordinates, and the gradient of its predicted split\n // mean. Identity link: noise σ² on every cell, covariance σ²(λI + Σ Q_uQ_uᵀ)⁻¹\n // over its observed units, gradient the mean loading. Logit link (Laplace):\n // a cell at pass rate p carries information p(1−p), covariance\n // (λI + Σ n_u p_u(1−p_u) Q_uQ_uᵀ)⁻¹, gradient the mean of p_u(1−p_u) Q_u.\n const meanLoading = new Array<number>(rank).fill(0)\n for (const loading of fit.loadings) {\n for (let d = 0; d < rank; d++) meanLoading[d]! += loading[d]! / units\n }\n const leaders = leaderRows.map((row) => {\n const point = fit.coordinates[row]!\n const information = fit.loadings.map((q, u) => {\n if (link === 'identity') return 1 / noiseVariance!\n const p = logistic(fit.bias[u]! + dot(point, q))\n return p * (1 - p)\n })\n const gradient =\n link === 'identity'\n ? meanLoading\n : Array.from({ length: rank }, (_, d) => {\n let total = 0\n for (let u = 0; u < units; u++)\n total += (information[u]! * fit.loadings[u]![d]!) / units\n return total\n })\n const prior = link === 'identity' ? ridge / noiseVariance! : ridge\n const system = Array.from({ length: rank }, (_, i) =>\n Array.from({ length: rank }, (_, j) => (i === j ? prior : 0)),\n )\n const counts = matrix.rows[row]!.counts\n for (const unit of matrix.rows[row]!.observed.keys()) {\n const q = fit.loadings[unit]!\n const weight = information[unit]! * (link === 'identity' ? 1 : counts.get(unit)!.count)\n for (let i = 0; i < rank; i++) {\n for (let j = 0; j < rank; j++) system[i]![j]! += weight * q[i]! * q[j]!\n }\n }\n return { information, gradient, covariance: choleskyInverse(cholesky(system)!) }\n })\n const shares = (sigmas: readonly (readonly (readonly number[])[])[]): number[] => {\n const toward = sigmas.map((sigma, index) =>\n sigma.map((line) => dot(line, leaders[index]!.gradient)),\n )\n const contrast = toward.map((vector, index) => dot(leaders[index]!.gradient, vector))\n return fit.loadings.map((q, u) => {\n const reduction = sigmas.map((sigma, index) => {\n const information = leaders[index]!.information[u]!\n if (!(information > 0)) return 0\n const spread = dot(\n q,\n sigma.map((line) => dot(line, q)),\n )\n return dot(toward[index]!, q) ** 2 / (1 / information + spread)\n })\n let share = 0\n let pairs = 0\n for (let i = 0; i < sigmas.length; i++) {\n for (let j = i + 1; j < sigmas.length; j++) {\n const variance = contrast[i]! + contrast[j]!\n if (variance > 0) share += (reduction[i]! + reduction[j]!) / variance\n pairs += 1\n }\n }\n return share / pairs\n })\n }\n const byShare = (values: readonly number[]) => (left: number, right: number) =>\n values[right]! - values[left]! ||\n compareCodeUnits(matrix.unitIds[left]!, matrix.unitIds[right]!)\n const covariance = leaders.map((leader) => leader.covariance)\n const first = shares(covariance)\n const ranked = matrix.unitIds\n .map((_, u) => u)\n .sort(byShare(first))\n .map((u) => ({\n unitId: matrix.unitIds[u]!,\n share: round9(first[u]!),\n measuredBy: leaderRows.filter((row) => matrix.rows[row]!.observed.has(u)).length,\n }))\n if (batch === null) return { ranked, batch: null, insufficient: null }\n // Greedy batch: pick the best unit, condition every leader on one more cell\n // of it, and pick again, so a batch spreads over the directions it needs.\n const among = new Set(batch.among ?? matrix.unitIds)\n const open = new Set(matrix.unitIds.flatMap((unitId, u) => (among.has(unitId) ? [u] : [])))\n const picked: string[] = []\n let sigmas: number[][][] = covariance\n while (picked.length < batch.count && open.size > 0) {\n const values = shares(sigmas)\n const best = [...open].sort(byShare(values))[0]!\n open.delete(best)\n picked.push(matrix.unitIds[best]!)\n const q = fit.loadings[best]!\n sigmas = sigmas.map((sigma, index) => {\n const information = leaders[index]!.information[best]!\n if (!(information > 0)) return sigma\n const toward = sigma.map((line) => dot(line, q))\n const denominator = 1 / information + dot(q, toward)\n return sigma.map((line, i) =>\n line.map((value, j) => value - (toward[i]! * toward[j]!) / denominator),\n )\n })\n }\n return { ranked, batch: picked, insufficient: null }\n}\n\n/**\n * The `asha` extension that adds, at each rung, the units that best separate\n * the leaders: the greedy `nextUnit` batch from `calibration`'s loadings,\n * with this search's nodes placed on them from the cells the ledger held when\n * the rung opened. The leaders are the lens's (the top 3 by predicted mean on\n * every calibrated unit). Where the lens cannot rank (fewer than 2 leaders,\n * or no measured noise), `asha` fills the rung from its seeded order.\n */\nexport function nextUnitExtension(\n calibration: SkillCalibration,\n options: { leaders?: number } = {},\n): SearchUnitExtension {\n const digest = hashCanonical(calibration).slice('sha256:'.length, 'sha256:'.length + 12)\n return {\n name: `next-unit(${digest})`,\n choose({ state, asOfSequence, split, remaining, count }) {\n const lens = skillManifold(state, calibration.rank, {\n split,\n calibration,\n asOfSequence,\n ...(options.leaders === undefined ? {} : { leaders: options.leaders }),\n batch: { count, among: remaining },\n })\n return lens.data.batch ?? []\n },\n }\n}\n\n// ── Small linear algebra ─────────────────────────────────────────────\n\nfunction dot(left: readonly number[], right: readonly number[]): number {\n let sum = 0\n for (let index = 0; index < left.length; index++) sum += left[index]! * right[index]!\n return sum\n}\n\nfunction mean(values: readonly number[]): number {\n return values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\nfunction transpose(matrix: readonly (readonly number[])[]): number[][] {\n return matrix[0] ? matrix[0].map((_, j) => matrix.map((row) => row[j]!)) : []\n}\n\nfunction multiply(\n left: readonly (readonly number[])[],\n right: readonly (readonly number[])[],\n): number[][] {\n return left.map((row) =>\n right[0]!.map((_, j) => row.reduce((sum, value, m) => sum + value * right[m]![j]!, 0)),\n )\n}\n\nfunction diagonal(values: readonly number[]): number[][] {\n return values.map((value, i) => values.map((_, j) => (i === j ? value : 0)))\n}\n\nfunction applyRow(vector: readonly number[], transform: readonly (readonly number[])[]): number[] {\n return transform[0]!.map((_, j) =>\n vector.reduce((sum, value, m) => sum + value * transform[m]![j]!, 0),\n )\n}\n\n/** Inverse of a lower-triangular matrix by forward substitution. */\nfunction lowerInverse(lower: readonly (readonly number[])[]): number[][] {\n const n = lower.length\n const inverse = Array.from({ length: n }, () => new Array<number>(n).fill(0))\n for (let j = 0; j < n; j++) {\n inverse[j]![j] = 1 / lower[j]![j]!\n for (let i = j + 1; i < n; i++) {\n let sum = 0\n for (let m = j; m < i; m++) sum += lower[i]![m]! * inverse[m]![j]!\n inverse[i]![j] = -sum / lower[i]![i]!\n }\n }\n return inverse\n}\n\n// ── Text ─────────────────────────────────────────────────────────────\n\n/** The manifold as text for a terminal or a proposer's context. */\nexport function formatSkillManifold(lens: GeometryLensResult<SkillManifoldData>): string {\n const { data, signal } = lens\n const lines: string[] = []\n const { matrix } = data\n lines.push(\n `Skill manifold (${data.split} split, ${data.mode === 'calibrated' ? `loadings from ${data.source}` : 'loadings fitted here'})`,\n )\n lines.push(\n ` matrix: ${plural(matrix.rows, 'node')} × ${plural(matrix.units, 'unit')}, ${matrix.observed} observed cells (density ${matrix.density === null ? 'unknown' : `${Math.round(matrix.density * 1000) / 10}%`}); left out ${plural(matrix.excludedNodes, 'node')} and ${plural(matrix.excludedUnits, 'unit')}${matrix.fitRows > 0 && matrix.fitRows < matrix.rows ? `; factors fitted on ${matrix.fitRows} evenly spaced rows` : ''}`,\n )\n const { intrinsicDimension: intrinsic } = data\n if (intrinsic.value === null) {\n lines.push(` intrinsic dimension: insufficient (${intrinsic.insufficient})`)\n } else {\n const curve = intrinsic.curve\n .map(\n (point) => `k=${point.rank} ${point.error.toFixed(3)}±${fixedOrDash(point.standardError)}`,\n )\n .join(', ')\n lines.push(\n ` intrinsic dimension: ${intrinsic.value} (${intrinsic.folds}-fold held-out ${data.model?.link === 'logit' ? 'binomial log loss' : 'squared error on the standardized scale'}, one-SE rule, ${intrinsic.n} held-out cells per rank: ${curve})`,\n )\n }\n if (data.model === null) {\n if (data.insufficient !== intrinsic.insufficient) {\n lines.push(` model: insufficient (${data.insufficient})`)\n }\n return lines.join('\\n')\n }\n const { model } = data\n const explained = data.explained\n const r2 = explained?.byRank.find((entry) => entry.rank === model.rank)?.r2\n const logit = model.link === 'logit'\n lines.push(\n ` model: ${logit ? 'item-response (two-parameter logistic, every cell 0 or 1)' : 'linear on standardized means'}, rank ${model.rank}, ridge ${model.ridge}, ${model.iterations} ${logit ? 'Newton' : 'ALS'} sweeps${model.converged ? '' : ' (not converged)'}${r2 === undefined ? '' : `, in-sample ${logit ? 'pseudo-R²' : 'R²'} ${r2.toFixed(3)} over unit ${logit ? 'easiness' : 'means'}`}${explained && explained.axisShare.length > 0 ? `; axis shares ${explained.axisShare.map((share) => `${Math.round(share * 1000) / 10}%`).join(', ')}` : ''}; ${logit ? 'cell noise binomial' : `cell noise ${data.noiseVariance === null ? 'unknown' : data.noiseVariance.toFixed(3)} (standardized)`}`,\n )\n const strongest = [...data.units]\n .sort((left, right) => right.strength - left.strength)\n .slice(0, 5)\n lines.push(\n ` units that separate nodes most: ${strongest.map((unit) => `${unit.unitId} (${unit.strength.toFixed(2)}, axis ${dominantAxis(unit.loading) + 1})`).join(', ')}`,\n )\n if (data.leaders.length > 0) {\n lines.push(\n ` leaders by predicted split mean: ${data.leaders.map((leader) => `${leader.nodeId} ${leader.predictedMean.toFixed(3)} on ${leader.observed} units`).join('; ')}`,\n )\n }\n if (signal.value === null) {\n lines.push(` next unit: insufficient (${signal.insufficient})`)\n } else {\n const top = data.nextUnits\n .slice(0, 5)\n .map(\n (unit) =>\n `${unit.unitId} ${(unit.share * 100).toFixed(1)}% (${unit.measuredBy}/${data.leaders.length} measured)`,\n )\n .join(', ')\n lines.push(\n ` next unit: ${signal.subject}, removing an expected ${(signal.value * 100).toFixed(1)}% of the leaders' contrast variance per cell; ranked: ${top}`,\n )\n }\n return lines.join('\\n')\n}\n\nfunction dominantAxis(loading: readonly number[]): number {\n let best = 0\n for (let index = 1; index < loading.length; index++) {\n if (Math.abs(loading[index]!) > Math.abs(loading[best]!)) best = index\n }\n return best\n}\n\nfunction fixedOrDash(value: number): string {\n return Number.isFinite(value) ? value.toFixed(3) : '–'\n}\n","/**\n * `taskMatrix(state)`: nodes × units, both clustered by a simple deterministic\n * method (search-tree-design §12). No numeric-matrix clustering primitive\n * exists elsewhere in agent-eval (`pipelines/failure-cluster.ts` groups by an\n * exact categorical key, not by distance over a score matrix), so this lens\n * adds one: single-linkage clustering with a data-derived\n * cutoff (the median of the finite pairwise distances), so nothing is a fixed\n * magic constant. Pairs without a shared observation have no direct link,\n * but can share a component through other items. A distance is the root mean square\n * difference over the observations both items share, so a pair measured on\n * 24 shared units is not farther apart than a pair on 6 only because it has\n * more terms.\n *\n * The signal, specialist gain per unit cluster, is the spread between a\n * cluster's best node and the mean of its nodes, in the objective's\n * direction: a large gap says some node specializes on that task family\n * rather than the field being uniform. Node means compare on shared units\n * only (a node contributes when it scored every unit of the cluster), a node\n * decided invalid never contributes, and a gain needs 2 contributing nodes\n * and 6 units (§6.4's `descriptive` threshold); below that it is null with\n * the reason, never 0.\n */\n\nimport type { SearchStateView } from '../../campaign/search-state'\nimport { compareCodeUnits } from '../../ledger-core/canonical'\nimport { evenSample } from './geometry'\nimport { INSUFFICIENT_FROM, rankingSplit } from './shared'\n\n// Pairwise scoring costs O(n²u + u²n), before sorting the distances. At 200\n// nodes, node clustering makes at most 39,800 distance calls instead of\n// 3,998,000 at 2,000 nodes (<1%); unit distances also scan only those 200.\nconst TASK_MATRIX_NODES = 200\n\nconst SPECIALIST_GAIN_METHOD = `per unit cluster, the best node's mean over the cluster's units minus the mean of the node means, in the objective's direction and the metric's units, among nodes not decided invalid that scored every unit of the cluster; reported from 2 such nodes and ${INSUFFICIENT_FROM} units; a point value with no interval: the largest of several noisy means exceeds their mean even when no node specializes, so read it against the spread of the node means`\n\nexport interface TaskMatrixCell {\n nodeId: string\n unitId: string\n /** Mean of the node's scored cells on this unit; absent (not zero) when\n * the node never scored the unit. */\n mean: number | null\n}\n\nexport interface TaskMatrixCluster {\n /** Stable id: the lexicographically first member. */\n id: string\n members: string[]\n}\n\nexport interface TaskMatrixSpecialistRow {\n clusterId: string\n unitIds: string[]\n /** Best node mean minus the mean of node means over the cluster's units,\n * oriented so a larger gain is a larger advantage in the objective's\n * direction. Null below 2 contributing nodes or below 6 units, with the\n * reason in `insufficient`: never reported as 0. */\n gain: number | null\n /** The contributing node with the best mean; null without one. */\n bestNodeId: string | null\n /** Nodes not decided invalid that scored every unit of the cluster. */\n nodesContributing: number\n /** Why `gain` is null; null when it is not. */\n insufficient: string | null\n}\n\nexport interface TaskMatrixData {\n split: 'train' | 'selection'\n direction: 'maximize' | 'minimize'\n /** How `specialistGain` is computed, including the node cap when sampled. */\n method: string\n /** Present only when nodes were sampled; absent for an unchanged full matrix. */\n sampling?: {\n nodesClustered: number\n nodesTotal: number\n cap: number\n }\n nodeIds: string[]\n unitIds: string[]\n nodeClusters: TaskMatrixCluster[]\n unitClusters: TaskMatrixCluster[]\n cells: TaskMatrixCell[]\n specialistGain: TaskMatrixSpecialistRow[]\n}\n\nexport interface TaskMatrixOptions {\n split?: 'train' | 'selection'\n}\n\n/** unitClusterId → specialist gain; a cluster whose gain is null (fewer than\n * 2 contributing nodes or 6 units) is omitted, not zeroed. */\nexport type TaskMatrixSignal = Record<string, number>\n\nexport function taskMatrix(\n state: SearchStateView,\n options: TaskMatrixOptions = {},\n): { data: TaskMatrixData; signal: { name: string; value: TaskMatrixSignal } } {\n const split = options.split ?? rankingSplit(state)\n const direction = state.header?.objective.direction ?? 'maximize'\n const sign = direction === 'maximize' ? 1 : -1\n const allNodeIds = state.nodeIds()\n // Use the same sample for both axes, cells, and specialist gains. Units\n // observed only on omitted nodes must not become empty matrix columns.\n const nodeIds = evenSample(allNodeIds, TASK_MATRIX_NODES)\n const sampling =\n nodeIds.length < allNodeIds.length\n ? { nodesClustered: nodeIds.length, nodesTotal: allNodeIds.length, cap: TASK_MATRIX_NODES }\n : null\n const invalid = new Set(\n state\n .nodes()\n .filter((node) => node.status === 'invalid')\n .map((node) => node.nodeId),\n )\n\n const byNodeUnit = new Map<string, Map<string, number>>()\n const unitSet = new Set<string>()\n for (const nodeId of nodeIds) {\n const units = new Map<string, number>()\n for (const unit of state.unitScores(nodeId, split)) {\n units.set(unit.unitId, unit.mean)\n unitSet.add(unit.unitId)\n }\n byNodeUnit.set(nodeId, units)\n }\n const unitIds = [...unitSet].sort(compareCodeUnits)\n\n const nodeClusters = clusterBy(nodeIds, (a, b) => nodeDistance(byNodeUnit, a, b))\n const unitClusters = clusterBy(unitIds, (a, b) => unitDistance(byNodeUnit, nodeIds, a, b))\n\n const orderedNodeIds = nodeClusters.flatMap((c) => c.members)\n const orderedUnitIds = unitClusters.flatMap((c) => c.members)\n\n const cells: TaskMatrixCell[] = []\n for (const nodeId of orderedNodeIds) {\n const units = byNodeUnit.get(nodeId)!\n for (const unitId of orderedUnitIds)\n cells.push({ nodeId, unitId, mean: units.get(unitId) ?? null })\n }\n\n const specialistGain: TaskMatrixSpecialistRow[] = unitClusters.map((cluster) => {\n // Oriented node means over the whole cluster, from nodes that scored\n // every unit of it, so every mean is over the same units.\n const contributing: Array<{ nodeId: string; oriented: number }> = []\n for (const nodeId of nodeIds) {\n if (invalid.has(nodeId)) continue\n const units = byNodeUnit.get(nodeId)!\n let total = 0\n let complete = true\n for (const unitId of cluster.members) {\n const value = units.get(unitId)\n if (value === undefined) {\n complete = false\n break\n }\n total += value\n }\n if (complete) contributing.push({ nodeId, oriented: (sign * total) / cluster.members.length })\n }\n let best: { nodeId: string; oriented: number } | null = null\n for (const entry of contributing)\n if (best === null || entry.oriented > best.oriented) best = entry\n const row = {\n clusterId: cluster.id,\n unitIds: cluster.members,\n bestNodeId: best?.nodeId ?? null,\n nodesContributing: contributing.length,\n }\n if (contributing.length < 2 || cluster.members.length < INSUFFICIENT_FROM) {\n return {\n ...row,\n gain: null,\n insufficient:\n contributing.length < 2\n ? `${contributing.length} node${contributing.length === 1 ? '' : 's'} scored every unit of the cluster; a gain needs 2`\n : `${cluster.members.length} of ${INSUFFICIENT_FROM} units`,\n }\n }\n const mean = contributing.reduce((sum, entry) => sum + entry.oriented, 0) / contributing.length\n return { ...row, gain: best!.oriented - mean, insufficient: null }\n })\n\n const signalValue: TaskMatrixSignal = {}\n for (const row of specialistGain) if (row.gain !== null) signalValue[row.clusterId] = row.gain\n\n return {\n data: {\n split,\n direction,\n method: sampling\n ? `${SPECIALIST_GAIN_METHOD}; node clustering, unit clustering, and specialist gains use ${sampling.nodesClustered} of ${sampling.nodesTotal} nodes, evenly sampled in registration order (cap ${sampling.cap})`\n : SPECIALIST_GAIN_METHOD,\n ...(sampling ? { sampling } : {}),\n nodeIds: orderedNodeIds,\n unitIds: orderedUnitIds,\n nodeClusters,\n unitClusters,\n cells,\n specialistGain,\n },\n signal: { name: 'taskMatrix.specialistGain', value: signalValue },\n }\n}\n\nfunction nodeDistance(byNodeUnit: Map<string, Map<string, number>>, a: string, b: string): number {\n const unitsA = byNodeUnit.get(a)!\n const unitsB = byNodeUnit.get(b)!\n let sumSquares = 0\n let shared = 0\n for (const [unitId, valueA] of unitsA) {\n const valueB = unitsB.get(unitId)\n if (valueB === undefined) continue\n sumSquares += (valueA - valueB) ** 2\n shared += 1\n }\n return shared === 0 ? Number.POSITIVE_INFINITY : Math.sqrt(sumSquares / shared)\n}\n\nfunction unitDistance(\n byNodeUnit: Map<string, Map<string, number>>,\n nodeIds: readonly string[],\n a: string,\n b: string,\n): number {\n let sumSquares = 0\n let shared = 0\n for (const nodeId of nodeIds) {\n const units = byNodeUnit.get(nodeId)!\n const valueA = units.get(a)\n const valueB = units.get(b)\n if (valueA === undefined || valueB === undefined) continue\n sumSquares += (valueA - valueB) ** 2\n shared += 1\n }\n return shared === 0 ? Number.POSITIVE_INFINITY : Math.sqrt(sumSquares / shared)\n}\n\n/**\n * Single-linkage connected components. The cutoff is the median of the\n * finite pairwise distances measured before any merge — a threshold the data\n * itself sets, not a constant this lens chooses. Only finite distances\n * connect a pair directly. Stopped at a cutoff,\n * single linkage yields the connected components of the graph whose edges\n * are the pairs at most the cutoff apart, so the merge order cannot change\n * the result. Each pair is measured at most twice, without rescanning merged\n * clusters. The clusters and their members are sorted by UTF-16 code unit,\n * never by the host's locale, so a cluster id is the same on every machine.\n */\nfunction clusterBy(\n ids: readonly string[],\n distance: (a: string, b: string) => number,\n): TaskMatrixCluster[] {\n if (ids.length <= 1) return ids.map((id) => toCluster([id]))\n\n const finite: number[] = []\n for (let i = 0; i < ids.length; i++) {\n for (let j = i + 1; j < ids.length; j++) {\n const d = distance(ids[i]!, ids[j]!)\n if (Number.isFinite(d)) finite.push(d)\n }\n }\n if (finite.length === 0) return ids.map((id) => toCluster([id]))\n finite.sort((a, b) => a - b)\n const cutoff = finite[Math.floor(finite.length / 2)]!\n\n const parents = ids.map((_, index) => index)\n function root(index: number): number {\n while (parents[index] !== index) {\n parents[index] = parents[parents[index]!]!\n index = parents[index]!\n }\n return index\n }\n for (let i = 0; i < ids.length; i++) {\n for (let j = i + 1; j < ids.length; j++) {\n if (distance(ids[i]!, ids[j]!) <= cutoff) parents[root(j)] = root(i)\n }\n }\n\n const clusters = new Map<number, string[]>()\n for (let i = 0; i < ids.length; i++) {\n const representative = root(i)\n const members = clusters.get(representative) ?? []\n members.push(ids[i]!)\n clusters.set(representative, members)\n }\n return [...clusters.values()].map(toCluster).sort((a, b) => compareCodeUnits(a.id, b.id))\n}\n\nfunction toCluster(members: string[]): TaskMatrixCluster {\n const sorted = [...members].sort(compareCodeUnits)\n return { id: sorted[0]!, members: sorted }\n}\n","/**\n * `tree(state)`: a tidy tree of nodes and edges — the current page (the base\n * view every other lens sits beside, search-tree-design §12).\n *\n * The design table names this lens's signal \"none (base view)\": it drives no\n * `SearchPolicy` and none of this group's policy wiring reads it. It still\n * returns the one named signal every lens returns, so a caller need not\n * special-case it: `tree.nodeCount`, the plain size of the tree.\n */\n\nimport type { SearchEdgeOperator, SearchNodeStatus } from '../../campaign/search-ledger-types'\nimport type { SearchStateView } from '../../campaign/search-state'\n\nexport interface TreeNode {\n nodeId: string\n status: SearchNodeStatus | null\n rung: number | null\n /** Edges from the root along primary parents; null when the node's\n * parents are unknown (an `unknown`-attribution edge, or a derived root). */\n depth: number | null\n cellCount: number\n /** The node's known spend. A partial when `unknownCostCells` is above 0:\n * those cells add at least `floorUsd` more, and their true cost is unknown. */\n knownCostUsd: number\n floorUsd: number\n unknownCostCells: number\n /** The operator of the edge that registered this node's primary parent;\n * null for the root and for a node whose parents are unknown. */\n operator: SearchEdgeOperator | null\n children: TreeNode[]\n}\n\nexport interface TreeData {\n /** Normally one entry (the search's root). More than one only when a node\n * has unknown parents (`primaryParentId === null` but it is not the\n * root): such a node is shown as its own top-level entry rather than\n * folded under the root it may or may not descend from. */\n roots: TreeNode[]\n nodeCount: number\n edgeCount: number\n}\n\nexport function tree(state: SearchStateView): {\n data: TreeData\n signal: { name: string; value: number }\n} {\n const nodes = state.nodes()\n const byId = new Map(nodes.map((node) => [node.nodeId, node]))\n const childrenOf = new Map<string, string[]>()\n const topLevel: string[] = []\n\n for (const node of nodes) {\n if (node.primaryParentId !== null && byId.has(node.primaryParentId)) {\n const list = childrenOf.get(node.primaryParentId)\n if (list) list.push(node.nodeId)\n else childrenOf.set(node.primaryParentId, [node.nodeId])\n } else {\n topLevel.push(node.nodeId)\n }\n }\n\n const primaryOperator = new Map<string, SearchEdgeOperator>()\n for (const edge of state.edges()) {\n const child = byId.get(edge.childNodeId)\n if (!child) continue\n const primaryParent = edge.parents[0]?.nodeId ?? null\n if (primaryParent === child.primaryParentId && !primaryOperator.has(child.nodeId)) {\n primaryOperator.set(child.nodeId, edge.operator)\n }\n }\n\n const build = (nodeId: string): TreeNode => {\n const node = byId.get(nodeId)!\n return {\n nodeId: node.nodeId,\n status: node.status,\n rung: node.rung,\n depth: node.depth,\n cellCount: node.cellCount,\n knownCostUsd: node.spend.knownUsd,\n floorUsd: node.spend.floorUsd,\n unknownCostCells: node.spend.unknownCostCells,\n operator: primaryOperator.get(node.nodeId) ?? null,\n children: (childrenOf.get(nodeId) ?? []).map((childId) => build(childId)),\n }\n }\n\n return {\n data: {\n roots: topLevel.map(build),\n nodeCount: nodes.length,\n edgeCount: state.edges().length,\n },\n signal: { name: 'tree.nodeCount', value: nodes.length },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAM,aAAa;AACnB,MAAM,YAAY;AAClB,MAAM,mBAAmB,+BAA+B,UAAU;AAClE,MAAM,oBAAoB;AAC1B,MAAM,4BAA4B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