pi-daddy 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/PRODUCT-GUIDE.md +125 -0
- package/README.md +16 -1
- package/REQUIREMENTS.md +41 -0
- package/dist/cli.d.ts +2 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +35 -7
- package/dist/cli.js.map +1 -1
- package/dist/daily-dashboard-host.d.ts +14 -1
- package/dist/daily-dashboard-host.d.ts.map +1 -1
- package/dist/daily-dashboard-host.js +40 -17
- package/dist/daily-dashboard-host.js.map +1 -1
- package/dist/daily-panel.d.ts +36 -0
- package/dist/daily-panel.d.ts.map +1 -0
- package/dist/daily-panel.js +84 -0
- package/dist/daily-panel.js.map +1 -0
- package/dist/daily-view-render.d.ts +2 -1
- package/dist/daily-view-render.d.ts.map +1 -1
- package/dist/daily-view-render.js +2 -1
- package/dist/daily-view-render.js.map +1 -1
- package/dist/daily-view.d.ts +3 -0
- package/dist/daily-view.d.ts.map +1 -1
- package/dist/daily-view.js +6 -0
- package/dist/daily-view.js.map +1 -1
- package/dist/dashboard-cli.d.ts +2 -0
- package/dist/dashboard-cli.d.ts.map +1 -1
- package/dist/dashboard-cli.js +37 -15
- package/dist/dashboard-cli.js.map +1 -1
- package/dist/dashboard-host-contract.d.ts +2 -0
- package/dist/dashboard-host-contract.d.ts.map +1 -1
- package/dist/dashboard-host-contract.js.map +1 -1
- package/dist/dashboard-host-transport.d.ts.map +1 -1
- package/dist/dashboard-host-transport.js +6 -3
- package/dist/dashboard-host-transport.js.map +1 -1
- package/dist/dashboard-host.d.ts +30 -2
- package/dist/dashboard-host.d.ts.map +1 -1
- package/dist/dashboard-host.js +73 -11
- package/dist/dashboard-host.js.map +1 -1
- package/dist/dashboard-menu.d.ts +16 -0
- package/dist/dashboard-menu.d.ts.map +1 -0
- package/dist/dashboard-menu.js +33 -0
- package/dist/dashboard-menu.js.map +1 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/learning-connection.d.ts +127 -0
- package/dist/learning-connection.d.ts.map +1 -0
- package/dist/learning-connection.js +54 -0
- package/dist/learning-connection.js.map +1 -0
- package/dist/measured-order.d.ts.map +1 -1
- package/dist/measured-order.js +63 -5
- package/dist/measured-order.js.map +1 -1
- package/dist/model-preflight.d.ts +5 -0
- package/dist/model-preflight.d.ts.map +1 -1
- package/dist/model-preflight.js +9 -0
- package/dist/model-preflight.js.map +1 -1
- package/dist/product-files.d.ts +6 -0
- package/dist/product-files.d.ts.map +1 -0
- package/dist/product-files.js +55 -0
- package/dist/product-files.js.map +1 -0
- package/dist/work-command.d.ts.map +1 -1
- package/dist/work-command.js +14 -6
- package/dist/work-command.js.map +1 -1
- package/dist/work-policy-registry.d.ts +133 -0
- package/dist/work-policy-registry.d.ts.map +1 -0
- package/dist/work-policy-registry.js +128 -0
- package/dist/work-policy-registry.js.map +1 -0
- package/dist/work-run.d.ts +56 -0
- package/dist/work-run.d.ts.map +1 -0
- package/dist/work-run.js +102 -0
- package/dist/work-run.js.map +1 -0
- package/dist/work-setup.d.ts +40 -0
- package/dist/work-setup.d.ts.map +1 -0
- package/dist/work-setup.js +174 -0
- package/dist/work-setup.js.map +1 -0
- package/extensions/daily-dashboard-session.ts +16 -7
- package/extensions/execute-child.ts +2 -2
- package/extensions/grants-command.ts +2 -2
- package/extensions/grants.ts +6 -2
- package/extensions/learning-outcome-session.ts +38 -0
- package/extensions/learning-session.ts +59 -0
- package/extensions/ordinary-runtime.ts +2 -2
- package/extensions/run-delegation.ts +2 -2
- package/extensions/work-policy-session.ts +139 -0
- package/extensions/work-run-session.ts +75 -0
- package/extensions/work-runtime.ts +2 -2
- package/extensions/work-session.ts +132 -0
- package/package.json +9 -1
- package/src/cli.ts +26 -7
- package/src/daily-dashboard-host.ts +32 -15
- package/src/daily-panel.ts +80 -0
- package/src/daily-view-render.ts +2 -1
- package/src/daily-view.ts +8 -0
- package/src/dashboard-cli.ts +29 -17
- package/src/dashboard-host-contract.ts +2 -0
- package/src/dashboard-host-transport.ts +7 -4
- package/src/dashboard-host.ts +48 -13
- package/src/dashboard-menu.ts +28 -0
- package/src/index.ts +7 -1
- package/src/learning-connection.ts +70 -0
- package/src/measured-order.ts +8 -3
- package/src/model-preflight.ts +9 -0
- package/src/product-files.ts +34 -0
- package/src/work-command.ts +11 -6
- package/src/work-policy-registry.ts +81 -0
- package/src/work-run.ts +79 -0
- package/src/work-setup.ts +141 -0
|
@@ -7,6 +7,8 @@ import { ENV_DASHBOARD_HOST_SOCKET } from "../src/dashboard-host-transport.ts";
|
|
|
7
7
|
import { startDailyDashboardHost } from "../src/daily-dashboard-host.ts";
|
|
8
8
|
import type { DeclaredWorkState } from "../src/work-command.ts";
|
|
9
9
|
import type { OrdinaryChildren } from "../src/ordinary-children.ts";
|
|
10
|
+
import { learningHarness, loadLearningConnection } from "../src/learning-connection.ts";
|
|
11
|
+
import { readProductJson } from "../src/product-files.ts";
|
|
10
12
|
|
|
11
13
|
const BRIDGE=Symbol.for("skill-harness.dashboard-host.v1"),idPattern=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
12
14
|
export function dailyDashboardPaths(cwd:string,id:string,home=homedir(),uid=process.getuid?.()??0){const key=createHash("sha256").update(`${cwd}\0${id}`).digest("hex");return {directory:join(home,".local","state","pi-daddy","hosts",key.slice(0,16)),socketDirectory:join("/tmp",`pi-daddy-${uid}`),socketPath:join("/tmp",`pi-daddy-${uid}`,`host-${key.slice(0,20)}.sock`)};}
|
|
@@ -18,22 +20,29 @@ export async function preparePrivateHostRoot(root:string):Promise<void>{
|
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
export function createDailyDashboardSession(input:{ordinary:()=>OrdinaryChildren;declared:()=>DeclaredWorkState|undefined;rebind:(state:DeclaredWorkState)=>void;cwd:()=>string;env:Record<string,string|undefined>;author:string;home?:string}){
|
|
21
|
-
let current:null|Awaited<ReturnType<typeof startDailyDashboardHost>>=null,publishedSocket:string|undefined,closing:null|{present:true;closing:true;evidenceDigest:string;expiresAt:number}=null;
|
|
23
|
+
let ended=false,current:null|Awaited<ReturnType<typeof startDailyDashboardHost>>=null,publishedSocket:string|undefined,closing:null|{present:true;closing:true;evidenceDigest:string;expiresAt:number}=null;
|
|
22
24
|
return Object.freeze({
|
|
25
|
+
get running(){return current!==null;},
|
|
26
|
+
async frame(){if(!current)throw Error("Start /grants host first");return current.host.frame();},
|
|
27
|
+
async choose(key:string,binding?:{tip:string;requestDigest:string}){if(!current)throw Error("Start /grants host first");if(binding)return current.host.humanAction(key,binding);const frame=await current.host.frame(),action=frame.actions.find(a=>a.key===key);if(!action)throw Error("Action unavailable at the current boundary");return current.host.humanAction(key,{tip:frame.tip,requestDigest:action.requestDigest});},
|
|
23
28
|
async run(target:string){
|
|
29
|
+
if(ended)throw Error("Original Pi session has ended; no host replacement or control recovery");
|
|
30
|
+
if(!target)target=`daily-${randomUUID().slice(0,8)}`;
|
|
24
31
|
if(target==="stop"){
|
|
25
32
|
if(!current)return "daily host is not running";await current.close();current=null;closing=null;if(publishedSocket&&input.env[ENV_DASHBOARD_HOST_SOCKET]===publishedSocket)delete input.env[ENV_DASHBOARD_HOST_SOCKET];publishedSocket=undefined;return "daily host stopped; no child was cancelled";
|
|
26
33
|
}
|
|
27
|
-
if(target==="closing"){if(!current)throw Error("daily host is not running");const expiresAt=Date.now()+120_000;closing={present:true,closing:true,evidenceDigest:createHash("sha256").update(`${input.cwd()}\0${expiresAt}\0${randomUUID()}`).digest("hex"),expiresAt};return "explicit closing presence recorded for two minutes; pause new dispatch and finish/cancel active attempts, then choose
|
|
34
|
+
if(target==="closing"){if(!current)throw Error("daily host is not running");const expiresAt=Date.now()+120_000;closing={present:true,closing:true,evidenceDigest:createHash("sha256").update(`${input.cwd()}\0${expiresAt}\0${randomUUID()}`).digest("hex"),expiresAt};return "explicit closing presence recorded for two minutes; pause new dispatch and finish/cancel active attempts, then choose Prepare retained case cards in the dashboard. No card is counted as delivered until visibly acknowledged.";}
|
|
28
35
|
if(!idPattern.test(target))throw Error("usage — /grants host <fresh-id> | closing | stop");if(current)throw Error("daily host already running in this session; use closing or stop");
|
|
29
|
-
const declared=input.declared();if(!declared)throw Error("declare current work first with
|
|
36
|
+
const declared=input.declared();if(!declared)throw Error("declare current work first with /grants work new");
|
|
30
37
|
const home=input.home??homedir(),paths=dailyDashboardPaths(input.cwd(),target,home),root=join(home,".local","state","pi-daddy","hosts");await preparePrivateHostRoot(root);await mkdir(paths.socketDirectory,{recursive:true,mode:0o700});
|
|
31
38
|
try{await lstat(paths.directory);throw Error(`host ID ${target} already has preserved state; choose a fresh host ID (the existing state was not opened, deleted or reused)`);}catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;}
|
|
32
|
-
const bridge=(globalThis as Record<PropertyKey,unknown>)[BRIDGE];if(!bridge)throw Error("loaded skill-harness extension bridge unavailable; load the
|
|
33
|
-
|
|
39
|
+
const bridge=(globalThis as Record<PropertyKey,unknown>)[BRIDGE];if(!bridge)throw Error("loaded skill-harness extension bridge unavailable; load the skill-harness extension in this Pi session");
|
|
40
|
+
const harness=adoptDashboardHarnessBridge(bridge),savedLearning=await readProductJson(join(input.cwd(),".pi","learning-workspace.json")),learning=savedLearning?await loadLearningConnection(input.cwd(),declared,learningHarness(harness),input.author):null;
|
|
41
|
+
try{current=await startDailyDashboardHost({id:target,cwd:input.cwd(),directory:paths.directory,socketPath:paths.socketPath,declared,ordinary:input.ordinary(),harness,author:input.author,...(learning?{learning:learning.connection}:{}),presence:()=>closing,onDeclaredWorkChanged:input.rebind});}catch(error){if((error as NodeJS.ErrnoException).code==="EEXIST")throw Error(`host ID ${target} could not start because state already exists; choose a fresh host ID. Existing state was preserved.`);throw error;}
|
|
34
42
|
publishedSocket=current.socketPath;input.env[ENV_DASHBOARD_HOST_SOCKET]=publishedSocket;
|
|
35
|
-
return `daily host started at ${publishedSocket}; current declared work/facts were captured. Run /grants dashboard
|
|
43
|
+
return `daily host started at ${publishedSocket}; current declared work/facts were captured. Run /grants dashboard for numbered actions or /grants work for work setup. Runtime remains unaccepted.`;
|
|
36
44
|
},
|
|
37
|
-
|
|
45
|
+
/** Called only when the original Pi session ends; no hold release or effect reconciliation. */
|
|
46
|
+
async close(){ended=true;if(current)await current.endSession();if(publishedSocket&&input.env[ENV_DASHBOARD_HOST_SOCKET]===publishedSocket)delete input.env[ENV_DASHBOARD_HOST_SOCKET];current=null;closing=null;publishedSocket=undefined;}
|
|
38
47
|
});
|
|
39
48
|
}
|
|
@@ -94,7 +94,7 @@ async function executeChildBody(input: {
|
|
|
94
94
|
childId: string;
|
|
95
95
|
executionId: string;
|
|
96
96
|
parentExecutionId: string | null;
|
|
97
|
-
toolCallId?: string;
|
|
97
|
+
toolCallId?: string; declaredWork?: GrantsSession["declaredWork"];
|
|
98
98
|
cwd: string;
|
|
99
99
|
preparedWorkspace?: PreparedWorkspace;
|
|
100
100
|
signal?: AbortSignal;
|
|
@@ -128,7 +128,7 @@ async function executeChildBody(input: {
|
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
130
|
const workAttempt = await beginDeclaredWorkAttempt({
|
|
131
|
-
session, plan, childId, executionId, parentExecutionId, toolCallId: input.toolCallId,
|
|
131
|
+
session, plan, childId, executionId, parentExecutionId, toolCallId: input.toolCallId, declaredWork: input.declaredWork,
|
|
132
132
|
preparedWorkspace, configuredTimeoutMs, startedAt,
|
|
133
133
|
});
|
|
134
134
|
|
|
@@ -76,12 +76,12 @@ export interface GrantsCommandContext {
|
|
|
76
76
|
const PREVIEW_LIMIT = 12;
|
|
77
77
|
|
|
78
78
|
/** The verbs `/grants` answers to. Anything else is refused rather than silently treated as no verb. */
|
|
79
|
-
const KNOWN_SUBCOMMANDS: readonly string[] = ["init", "host", "variants", "dashboard", "ledger", "approvals", "revoke"];
|
|
79
|
+
const KNOWN_SUBCOMMANDS: readonly string[] = ["work", "learning", "init", "host", "variants", "dashboard", "ledger", "approvals", "revoke"];
|
|
80
80
|
|
|
81
81
|
export const grantsCommand = {
|
|
82
82
|
description:
|
|
83
83
|
"Show this session's capability grant, delegation depth, and known agent-type ceilings; " +
|
|
84
|
-
"/grants
|
|
84
|
+
"/grants work (setup/run/results) | /grants learning | /grants host [fresh-id]|stop | /grants dashboard | /grants approvals | /grants ledger",
|
|
85
85
|
handler: async (args: string, ctx: any) => {
|
|
86
86
|
// Everything this command may see, named in one place. Previously these were whatever happened to be in
|
|
87
87
|
// the enclosing closure — which is how a diagnostic came to disagree with the enforcer (R-28).
|
package/extensions/grants.ts
CHANGED
|
@@ -48,6 +48,8 @@ import { defaultDashboardPaths, offerDashboardHandshake, openDashboardCommand }
|
|
|
48
48
|
import { associateOrdinaryHost, ordinaryChildrenFor } from "../src/ordinary-children.ts";
|
|
49
49
|
import { loadDeclaredWork } from "../src/work-command.ts";
|
|
50
50
|
import { createDailyDashboardSession } from "./daily-dashboard-session.ts";
|
|
51
|
+
import { createWorkSession } from "./work-session.ts";
|
|
52
|
+
import { createLearningSession } from "./learning-session.ts";
|
|
51
53
|
import { replacePublishedDailyWork, type PublishedDailyWork } from "./daily-work-session.ts";
|
|
52
54
|
export default function (pi: ExtensionAPI) {
|
|
53
55
|
// The path pi loads as the extension, so a child granted `tool:delegate` can be started with `-e <this>`.
|
|
@@ -70,6 +72,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
70
72
|
// dispatch surface; afterwards this callback refreshes their model-facing spawnable-definition text.
|
|
71
73
|
const delegation = { refreshSpawnable: () => {} };
|
|
72
74
|
const publishedDailyWork: PublishedDailyWork = {};
|
|
75
|
+
const workSession=createWorkSession(session,dailyHost,()=>replacePublishedDailyWork(process.env,publishedDailyWork,session.declaredWork));
|
|
76
|
+
const learningSession=createLearningSession(dailyHost);
|
|
73
77
|
|
|
74
78
|
pi.on("session_start", async (_event, ctx) => {
|
|
75
79
|
// Real SDK contexts always supply SessionManager. The fallback keeps lightweight wiring fixtures
|
|
@@ -253,7 +257,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
253
257
|
* installed here for the reason R-62 gives: it would turn pi's "interrupt this turn" into "exit pi".
|
|
254
258
|
*/
|
|
255
259
|
pi.on("session_shutdown", async () => {
|
|
256
|
-
await dailyHost.close().catch(() => undefined);
|
|
260
|
+
await workSession.close(); await dailyHost.close().catch(() => undefined);
|
|
257
261
|
});
|
|
258
262
|
|
|
259
263
|
pi.on("agent_settled", async () => {
|
|
@@ -349,7 +353,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
349
353
|
...grantsCommand,
|
|
350
354
|
// Built per invocation and spelled out field by field, rather than passing the session whole: what a
|
|
351
355
|
// read-only diagnostic may see is a decision, and `GrantsCommandContext` is where it is recorded.
|
|
352
|
-
handler: (args, ctx) =>
|
|
356
|
+
handler: (args, ctx) => /^learning(?:\s|$)/.test(args.trim()) ? learningSession.run(args.trim().slice(8).trim(),ctx).catch(error=>{ctx.ui.notify(String(error),"error");}) : /^work(?:\s|$)/.test(args.trim()) ? workSession.run(args.trim().slice(4).trim(),ctx).catch(error=>{ctx.ui.notify(String(error),"error");}) :
|
|
353
357
|
grantsCommand.handler(args, {
|
|
354
358
|
...ctx,
|
|
355
359
|
grants: {
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { inspectWorkRun, type WorkRunInitial } from "../src/work-run.ts";
|
|
5
|
+
import type { ControlBinding } from "../src/control-journal.ts";
|
|
6
|
+
import { readProductJson } from "../src/product-files.ts";
|
|
7
|
+
import { readDailySnapshot } from "../src/daily-view-input.ts";
|
|
8
|
+
import { experimentHash } from "../src/experiment-contract.ts";
|
|
9
|
+
import type { LearningHarness, LearningWorkspace } from "../src/learning-connection.ts";
|
|
10
|
+
import type { DeclaredWorkState } from "../src/work-command.ts";
|
|
11
|
+
import type { ProductionObservation } from "../src/vendor/adoption.ts";
|
|
12
|
+
|
|
13
|
+
/** Link actual later-run bytes/pin; only an explicit independent human supplies outcome labels. */
|
|
14
|
+
export async function linkLatestWorkOutcome(ctx: ExtensionCommandContext, state: DeclaredWorkState, workspace: LearningWorkspace, harness: LearningHarness) {
|
|
15
|
+
const binding = await readProductJson(join(ctx.cwd, ".pi", "work-last-run.json")) as ControlBinding<WorkRunInitial> | null;
|
|
16
|
+
if (!binding) throw Error("No retained later bounded order is available");
|
|
17
|
+
const run = await inspectWorkRun(binding), pin = binding.initial.policyPin;
|
|
18
|
+
if (!pin?.adoptionId) throw Error("This run was not pinned to an adoption. It cannot establish an adopted outcome.");
|
|
19
|
+
const comparisons = workspace.inspect(Date.now()).comparisons.filter(c => c.state !== "deferred" && workspace.preparedAdoption(c.name)?.id === pin.adoptionId);
|
|
20
|
+
if(!comparisons.length)throw Error("No ready learning comparison matches this run's actual adoption pin. Reconnect original evidence before linking outcomes.");
|
|
21
|
+
const labels = comparisons.map((c, i) => `${i + 1}. ${c.title}`), picked = await ctx.ui.select("Observed adoption", labels), comparison = comparisons[labels.indexOf(picked ?? "")]; if (!comparison) return;
|
|
22
|
+
const rows = run.tasks.filter(t => t.resultPath && t.resultDigest), tasks = rows.map((t, i) => `${i + 1}. ${t.id}: ${t.state}`), selected = await ctx.ui.select("Actual retained output", tasks), row = rows[tasks.indexOf(selected ?? "")]; if (!row) return;
|
|
23
|
+
if (row.resultPath !== join(binding.directory, `${row.id}.txt`)) throw Error("retained result path changed");
|
|
24
|
+
const source = await readDailySnapshot(row.resultPath, 1024 * 1024);
|
|
25
|
+
if (source.status !== "read" || source.sha256 !== row.resultDigest) throw Error("retained output missing or mismatched");
|
|
26
|
+
await ctx.ui.editor("Complete retained output (controls escaped; editor edits discarded)", new TextDecoder("utf8", { fatal: true }).decode(source.bytes).replace(/[\p{Cc}\p{Cf}]/gu, c => c === "\n" || c === "\t" ? c : `\\u${c.charCodeAt(0).toString(16).padStart(4,"0")}`));
|
|
27
|
+
const outcomes = ["Unknown / not independently judged", "Independently confirmed success", "Independently confirmed defect"], outcome = await ctx.ui.select("Observed quality — runtime success is not a label", outcomes); if (!outcome) return;
|
|
28
|
+
const note = await ctx.ui.editor("Independent observation note / evidence (do not infer acceptance)", ""); if (!note?.trim()) return;
|
|
29
|
+
if (!await ctx.ui.confirm("Retain this scoped observation?", "This records an explicit human observation of these exact later-work bytes. Acceptance remains absent. It does not calibrate a detector, certify held-out improvement or trigger rollback.")) return;
|
|
30
|
+
const root = workspace.configuration().archiveRoot;
|
|
31
|
+
const artifact = harness.retainArchiveSource(root, { sourceId: `later-output-${source.sha256.slice(0,24)}`, parser: { id: "producer-work-output", version: "1" }, retention: "exact", bytes: source.bytes }).manifestId;
|
|
32
|
+
const evidence = harness.retainArchiveSource(root, { sourceId: `later-observation-${randomUUID()}`, parser: { id: "producer-work-observation", version: "1" }, retention: "exact", bytes: Buffer.from(JSON.stringify({ run: binding.initial, task: row, note, author: workspace.configuration().author })) }).manifestId;
|
|
33
|
+
const input: ProductionObservation = { id: `work-observation-${experimentHash({run:binding.initial.runId,task:row.id,note,outcome}).slice(0,24)}`, adoptionId: pin.adoptionId, candidateDigest: pin.candidateDigest, scopeDigest: pin.scopeDigest, originalRequirementDigest: binding.initial.selectionDigest, currentRequirementDigest: state.selectedSnapshot.snapshot.digest, outcome: outcomes.indexOf(outcome) === 1 ? "success" : outcomes.indexOf(outcome) === 2 ? "confirmed-defect" : "unknown", acceptanceDigest: null, acceptedArtifactDigest: null, observedArtifactDigest: source.sha256, evidence: [artifact, evidence] };
|
|
34
|
+
const preview = workspace.previewObservation(comparison.name, input);
|
|
35
|
+
if (!await ctx.ui.confirm("Confirm classified outcome", JSON.stringify(preview.classification))) return;
|
|
36
|
+
const retained = workspace.observe(comparison.name, input, [preview.digest]);
|
|
37
|
+
ctx.ui.notify(`Observed outcome retained (${retained.manifestId.slice(0,12)}). No acceptance, calibration or automatic rollback inferred.`, "info");
|
|
38
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { mkdir } from "node:fs/promises";
|
|
5
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { adoptDashboardHarnessBridge } from "../src/dashboard-harness.ts";
|
|
7
|
+
import { learningHarness, bindLearningConnection, loadLearningConnection, learningScopeDigest, type LearningUI } from "../src/learning-connection.ts";
|
|
8
|
+
import { loadDeclaredWork } from "../src/work-command.ts";
|
|
9
|
+
import { privateDirectory } from "../src/product-files.ts";
|
|
10
|
+
import { workPolicyMenu } from "./work-policy-session.ts";
|
|
11
|
+
import { linkLatestWorkOutcome } from "./learning-outcome-session.ts";
|
|
12
|
+
import type { createDailyDashboardSession } from "./daily-dashboard-session.ts";
|
|
13
|
+
|
|
14
|
+
/** Normal human-only entrypoint: delegates canonical learning decisions to the loaded harness wizard. */
|
|
15
|
+
export function createLearningSession(host: ReturnType<typeof createDailyDashboardSession>) {
|
|
16
|
+
let busy = false;
|
|
17
|
+
return { async run(_verb: string, ctx: ExtensionCommandContext) {
|
|
18
|
+
if (busy) throw Error("A learning dialog is already open");
|
|
19
|
+
if (!ctx.hasUI) throw Error("Open /grants learning in interactive Pi");
|
|
20
|
+
busy = true;
|
|
21
|
+
try {
|
|
22
|
+
const declared = await loadDeclaredWork(join(ctx.cwd, ".pi", "work-current.json"));
|
|
23
|
+
if (!declared) throw Error("Declare work with /grants work first so learning has an exact scope");
|
|
24
|
+
const bridge = (globalThis as Record<PropertyKey, unknown>)[Symbol.for("skill-harness.dashboard-host.v1")];
|
|
25
|
+
const h = learningHarness(adoptDashboardHarnessBridge(bridge));
|
|
26
|
+
let connected: Awaited<ReturnType<typeof loadLearningConnection>> = null;
|
|
27
|
+
try { connected = await loadLearningConnection(ctx.cwd, declared, h, "local-operator"); }
|
|
28
|
+
catch (error) { ctx.ui.notify(String(error), "warning"); }
|
|
29
|
+
const menu = ["Open cases, comparisons, trust and outcomes", "Create learning workspace for selected work", "Connect existing learning workspace", "Adoption / rollback for next orders", "Retain current work for learning", "Link observed result from latest adopted order"];
|
|
30
|
+
const choice = await ctx.ui.select(connected ? "Learning — deliberate review (not earned automatic exposure)" : "Learning not connected", connected ? menu : menu.slice(1, 3));
|
|
31
|
+
if (!choice) return;
|
|
32
|
+
if ([menu[1], menu[2]].includes(choice)) {
|
|
33
|
+
if (host.running && !await ctx.ui.confirm("Reconnect learning after stopping the current host?", "Old host evidence is preserved. No child is cancelled. Start /grants host again after configuration.")) return;
|
|
34
|
+
if (host.running) await host.run("stop");
|
|
35
|
+
let directory: string;
|
|
36
|
+
if (choice === menu[1]) {
|
|
37
|
+
if (!await ctx.ui.confirm("Enable scoped learning retention?", "Case/comparison/trust decisions and explicitly selected output artifacts will be retained privately. No model is called; no quality, calibration or authority is invented.")) return;
|
|
38
|
+
const root = join(homedir(), ".local", "state", "pi-daddy", "learning"); await mkdir(root, { recursive: true, mode: 0o700 }); await privateDirectory(root);
|
|
39
|
+
const instance = join(root, randomUUID()); await privateDirectory(instance);
|
|
40
|
+
directory = join(instance, "workspace");
|
|
41
|
+
h.createLearningWorkspace(directory, { archiveRoot: join(instance, "archive"), scopeDigest: learningScopeDigest(declared), population: `work:${learningScopeDigest(declared).slice(0, 32)}`, author: "local-operator" });
|
|
42
|
+
} else { const path = await ctx.ui.input("Existing learning workspace directory"); if (!path) return; directory = path.trim(); }
|
|
43
|
+
await bindLearningConnection(ctx.cwd, declared, directory, h, "local-operator");
|
|
44
|
+
connected = await loadLearningConnection(ctx.cwd, declared, h, "local-operator");
|
|
45
|
+
ctx.ui.notify("Learning connected to exact work scope. Start /grants host to show it in Herdr.", "info");
|
|
46
|
+
}
|
|
47
|
+
if (!connected) throw Error("Connect learning first");
|
|
48
|
+
if (choice === menu[5]) { await linkLatestWorkOutcome(ctx, declared, connected.workspace, h); return; }
|
|
49
|
+
if (choice === menu[3]) { await workPolicyMenu(ctx, declared, connected.workspace, h); return; }
|
|
50
|
+
if (choice === menu[4]) {
|
|
51
|
+
if (!host.running) throw Error("Start /grants host first; it captures and binds the current work case batch through the existing archive policy");
|
|
52
|
+
await host.choose("refresh-current-work"); ctx.ui.notify("Current work retained. Open Learning for real case readiness; this is not a defect label.", "info"); return;
|
|
53
|
+
}
|
|
54
|
+
const ui: LearningUI = { select: (title, choices) => ctx.ui.select(title, choices), input: (title, initial) => ctx.ui.input(title, initial), editor: (title, text) => ctx.ui.editor(title, text), confirm: (title, detail) => ctx.ui.confirm(title, detail), notify: (text, level) => ctx.ui.notify(text, level ?? "info") };
|
|
55
|
+
await h.runLearningWizard({ directory: connected.connection.directory, cwd: ctx.cwd, ui });
|
|
56
|
+
if (host.running) ctx.ui.notify("Learning saved. If you changed trust configuration, stop/start /grants host explicitly to bind it; attention is not reset.", "info");
|
|
57
|
+
} finally { busy = false; }
|
|
58
|
+
} };
|
|
59
|
+
}
|
|
@@ -5,9 +5,9 @@ import { releaseDelegationWorkspace,type PreparedWorkspace } from "./workspace-r
|
|
|
5
5
|
import type { GrantsSession } from "./session.ts";
|
|
6
6
|
import type { DelegationOutcome } from "./execute-child.ts";
|
|
7
7
|
/** One wrapper around the original executor. It neither consumes nor replaces the caller's promise. */
|
|
8
|
-
export async function withOrdinaryChild(input:{session:GrantsSession;executionId:string;parentExecutionId:string|null;childId:string;toolCallId?:string;signal?:AbortSignal;preparedWorkspace?:PreparedWorkspace},operation:(signal?:AbortSignal)=>Promise<DelegationOutcome>){
|
|
8
|
+
export async function withOrdinaryChild(input:{session:GrantsSession;executionId:string;parentExecutionId:string|null;childId:string;toolCallId?:string;signal?:AbortSignal;preparedWorkspace?:PreparedWorkspace;declaredWork?:GrantsSession["declaredWork"]},operation:(signal?:AbortSignal)=>Promise<DelegationOutcome>){
|
|
9
9
|
let retained:ReturnType<typeof retainSessionChild>;
|
|
10
|
-
try{retained=retainSessionChild(input.session,{executionId:input.executionId,parentExecutionId:input.parentExecutionId,toolCallId:input.toolCallId??null},input.signal);}
|
|
10
|
+
try{if(input.declaredWork&&dataDigest(input.declaredWork.selectedSnapshot)!==dataDigest(input.session.declaredWork?.selectedSnapshot??null))throw Error("declared work changed before original child admission");retained=retainSessionChild(input.session,{executionId:input.executionId,parentExecutionId:input.parentExecutionId,toolCallId:input.toolCallId??null},input.signal);}
|
|
11
11
|
catch(error){return runWithFinalizers(async()=>{throw error;},[{label:"ordinary admission workspace release",run:async()=>{await releaseDelegationWorkspace({prepared:input.preparedWorkspace,childId:input.childId,executionId:input.executionId,parentExecutionId:input.parentExecutionId,ledgerPath:input.session.ledgerPath,reason:"refused"});}}]);}
|
|
12
12
|
try{const outcome=await operation(retained?.signal??input.signal);retained?.settle({ok:outcome.ok,exitCode:outcome.exitCode,aborted:outcome.aborted??false,outputDigest:dataDigest(outcome.text)},outcome.control??"not-assessed",outcome.control==="failed"?"not-assessed":outcome.control??"not-assessed");return outcome;}
|
|
13
13
|
catch(error){retained?.settle({failure:"original executor threw; inspect original caller"},"unknown");throw error;}
|
|
@@ -204,7 +204,7 @@ export async function runOneDelegation(
|
|
|
204
204
|
*/
|
|
205
205
|
options: {
|
|
206
206
|
/** Actual public execute argument, never read from model-authored correlation or output. */
|
|
207
|
-
toolCallId?: string;
|
|
207
|
+
toolCallId?: string; declaredWork?: GrantsSession["declaredWork"];
|
|
208
208
|
/** Progress for the parent's status block (ADR-0032). Display only. */
|
|
209
209
|
onProgress?: (update: {
|
|
210
210
|
/** Appended (process executor: a genuine byte stream). */
|
|
@@ -389,7 +389,7 @@ export async function runOneDelegation(
|
|
|
389
389
|
childId: ids.childId,
|
|
390
390
|
executionId: ids.executionId,
|
|
391
391
|
parentExecutionId: ids.parentExecutionId,
|
|
392
|
-
toolCallId: options.toolCallId,
|
|
392
|
+
toolCallId: options.toolCallId, declaredWork: options.declaredWork,
|
|
393
393
|
cwd: ctx.cwd,
|
|
394
394
|
preparedWorkspace,
|
|
395
395
|
signal,
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { mkdir, readdir } from "node:fs/promises";
|
|
5
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { supportedModelEfforts as getSupportedThinkingLevels } from "../src/model-preflight.ts";
|
|
7
|
+
import { createWorkPolicyRegistry, openWorkPolicyRegistry, policyForSetup, workPolicy, workPolicyDigest, workPolicyActivationDigest, type WorkPolicy, type WorkPolicyRegistry, type WorkPolicyActivation } from "../src/work-policy-registry.ts";
|
|
8
|
+
import { loadWorkSetup, type WorkSetup } from "../src/work-setup.ts";
|
|
9
|
+
import { bindLearningAdoption, learningScopeDigest, type LearningHarness, type LearningWorkspace } from "../src/learning-connection.ts";
|
|
10
|
+
import type { DeclaredWorkState } from "../src/work-command.ts";
|
|
11
|
+
import { privateDirectory, readProductJson, writeProductJson } from "../src/product-files.ts";
|
|
12
|
+
import type { AdoptionBinding, AdoptionFacts } from "../src/vendor/adoption.ts";
|
|
13
|
+
import type { FactoryAuthority } from "../src/factory-contract.ts";
|
|
14
|
+
import { experimentHash } from "../src/experiment-contract.ts";
|
|
15
|
+
|
|
16
|
+
const descriptor = (cwd: string) => join(cwd, ".pi", "work-policy-registry.json");
|
|
17
|
+
const policyPath = (cwd: string, digest: string) => join(cwd, ".pi", "work-policies", `${digest}.json`);
|
|
18
|
+
const registryHistoryPath=(cwd:string,scope:string)=>join(cwd,".pi","work-registry-bindings",`${scope}.json`);
|
|
19
|
+
async function retainRegistryBinding(cwd:string,binding:WorkPolicyRegistry){const path=registryHistoryPath(cwd,binding.initial.scopeDigest),old=await readProductJson(path);if(old&&experimentHash(old)!==experimentHash(binding))throw Error("scoped registry binding history conflict");if(!old)await writeProductJson(path,binding);}
|
|
20
|
+
function authority(id: string, binding?: AdoptionBinding, facts?: AdoptionFacts): FactoryAuthority { return { id, orderDigests: [], decisionDigests: [], activationDigests: [], migrationDigests: [], adoption: { id, adoptions: binding ? [binding.id] : [], rollbacks: [] }, facts: binding && facts ? [{ bindingId: binding.id, facts }] : [] }; }
|
|
21
|
+
async function independentFacts(ctx: ExtensionCommandContext, b: AdoptionBinding): Promise<AdoptionFacts | null> {
|
|
22
|
+
if (!await ctx.ui.confirm("Independent eligibility attestation — not a quality preference", `Have you independently verified that this exact comparison/candidate meets the scoped assessment policy, and is still eligible?\nExperiment: ${b.experimentDigest}\nCandidate: ${b.candidateDigest}\nScope: ${b.scopeDigest}\nAssessment: ${b.assessmentPolicyDigest}\n\nConfirm only with real independent evidence. Missing/uncertain evidence means No. This does not fabricate calibration or accept any result.`)) return null;
|
|
23
|
+
return { experimentDigest: b.experimentDigest, candidateDigest: b.candidateDigest, scopeDigest: b.scopeDigest, assessmentPolicyDigest: b.assessmentPolicyDigest, eligible: true };
|
|
24
|
+
}
|
|
25
|
+
export async function loadWorkPolicyRegistry(cwd: string, state: DeclaredWorkState): Promise<WorkPolicyRegistry | null> {
|
|
26
|
+
const binding = await readProductJson(descriptor(cwd)) as WorkPolicyRegistry | null;
|
|
27
|
+
if (binding && binding.initial.scopeDigest !== learningScopeDigest(state)) throw Error("Configured adoption registry belongs to different work. Use /grants learning → Adoption / rollback to reconnect or create scoped settings; no adopted setting was carried forward.");
|
|
28
|
+
if (binding) await openWorkPolicyRegistry(binding).inspect(); return binding;
|
|
29
|
+
}
|
|
30
|
+
async function savePolicy(cwd: string, name: string, policy: WorkPolicy) {
|
|
31
|
+
if(typeof name!=="string"||!name.trim()||Buffer.byteLength(name)>128||/[\p{Cc}\p{Cf}]/u.test(name))throw Error("bounded plain candidate name required");
|
|
32
|
+
const path = policyPath(cwd, workPolicyDigest(policy)), old = await readProductJson(path);
|
|
33
|
+
if(old){await readPolicy(cwd,workPolicyDigest(policy));return;}
|
|
34
|
+
await writeProductJson(path, { version: "named-work-policy-v1", name, policy });
|
|
35
|
+
}
|
|
36
|
+
async function readPolicy(cwd: string, digest: string) {
|
|
37
|
+
const saved = await readProductJson(policyPath(cwd, digest)) as { version: string; name: string; policy: WorkPolicy } | null;
|
|
38
|
+
if (!saved || Object.keys(saved).sort().join()!=="name,policy,version" || typeof saved.name!=="string" || !saved.name.trim() || Buffer.byteLength(saved.name)>128 || /[\p{Cc}\p{Cf}]/u.test(saved.name) || saved.version !== "named-work-policy-v1" || workPolicyDigest(saved.policy) !== digest) throw Error("Exact candidate policy bytes are missing; prepare the candidate profile first");
|
|
39
|
+
return workPolicy(saved.policy);
|
|
40
|
+
}
|
|
41
|
+
function retain(h: LearningHarness, root: string, parser: string, value: unknown) {
|
|
42
|
+
return h.retainArchiveSource(root, { sourceId: `${parser}-${experimentHash(value).slice(0, 24)}`, parser: { id: parser, version: "1" }, retention: "exact", bytes: Buffer.from(JSON.stringify(value)) }).manifestId;
|
|
43
|
+
}
|
|
44
|
+
export async function workPolicyMenu(ctx: ExtensionCommandContext, state: DeclaredWorkState, workspace: LearningWorkspace, harness: LearningHarness): Promise<void> {
|
|
45
|
+
const setup = await loadWorkSetup(state); if (!setup) throw Error("Declare a multi-task work setup before configuring ordinary model/effort adoption");
|
|
46
|
+
let binding = await readProductJson(descriptor(ctx.cwd)) as WorkPolicyRegistry|null;
|
|
47
|
+
if(binding)await openWorkPolicyRegistry(binding).inspect();
|
|
48
|
+
if(binding&&binding.initial.scopeDigest!==learningScopeDigest(state)){
|
|
49
|
+
if(!await ctx.ui.confirm("Settings belong to different selected work","Connect settings for this exact work scope? Previous registry and active/history-bearing orders remain untouched. No adopted setting carries across scopes."))return;
|
|
50
|
+
await retainRegistryBinding(ctx.cwd,binding);binding=null;
|
|
51
|
+
}
|
|
52
|
+
if(!binding){
|
|
53
|
+
const saved=await readProductJson(registryHistoryPath(ctx.cwd,learningScopeDigest(state))) as WorkPolicyRegistry|null;
|
|
54
|
+
if(saved){const view=await openWorkPolicyRegistry(saved).inspect();if(view.scopeDigest!==learningScopeDigest(state))throw Error("saved registry scope mismatch");if(!await ctx.ui.confirm("Reconnect saved settings for this work?",`${view.candidate.profiles.map(p=>`${p.model} / ${p.thinking}`).join(", ")}\nFuture runs still require current eligibility; existing runs do not migrate.`))return;binding=saved;await writeProductJson(descriptor(ctx.cwd),binding,true);}
|
|
55
|
+
}
|
|
56
|
+
if (!binding) {
|
|
57
|
+
const baseline = policyForSetup(setup.setup, learningScopeDigest(state), state.policy.digest);
|
|
58
|
+
if (!await ctx.ui.confirm("Create a scoped next-order registry?", "Baseline is the selected task models/effort. Future adoption can only change model/effort for these same definitions. No existing or active run changes.")) return;
|
|
59
|
+
const root = join(homedir(), ".local", "state", "pi-daddy", "work-registries"); await mkdir(root, { recursive: true, mode: 0o700 }); await privateDirectory(root);
|
|
60
|
+
binding = await createWorkPolicyRegistry({ directory: join(root, randomUUID()), authorityId: "local-operator", baseline });
|
|
61
|
+
await savePolicy(ctx.cwd, "Baseline", baseline); await retainRegistryBinding(ctx.cwd,binding); await writeProductJson(descriptor(ctx.cwd), binding, true);
|
|
62
|
+
}
|
|
63
|
+
const registry = openWorkPolicyRegistry(binding), current = await registry.inspect();
|
|
64
|
+
const menu = ["Prepare candidate model/effort profile", "Activate adopted comparison for next orders", "Roll back active adoption", "Inspect registry", "Recover learning link (no registry change)"];
|
|
65
|
+
const choice = await ctx.ui.select("Scoped settings — existing runs stay pinned", menu);
|
|
66
|
+
if (!choice) return;
|
|
67
|
+
if (choice === menu[3]) { await ctx.ui.editor("Registry details (read-only; editor changes are discarded)", JSON.stringify(current, null, 2)); return; }
|
|
68
|
+
if (choice === menu[0]) {
|
|
69
|
+
const candidate = structuredClone(current.candidate);
|
|
70
|
+
for (const profile of candidate.profiles) {
|
|
71
|
+
const models = ctx.scopedModels?.length ? ctx.scopedModels.map(entry => entry.model) : ctx.modelRegistry.getAvailable();
|
|
72
|
+
if(!models.length)throw Error("No available Pi models. Configure a model in Pi, then reopen settings; no fallback is chosen.");
|
|
73
|
+
const labels = models.map(m => `${m.provider}/${m.id}`), selected = await ctx.ui.select(`Model for ${setup.setup.tasks.find(t => t.id === profile.taskId)!.outcome}`, labels), model = models[labels.indexOf(selected ?? "")]; if (!model) return;
|
|
74
|
+
const thinking = await ctx.ui.select("Requested effort", getSupportedThinkingLevels(model)); if (!thinking) return;
|
|
75
|
+
profile.model = `${model.provider}/${model.id}`; profile.thinking = thinking as typeof profile.thinking;
|
|
76
|
+
}
|
|
77
|
+
const name = await ctx.ui.input("Candidate name", "Alternative profile"); if (!name?.trim()) return;
|
|
78
|
+
await savePolicy(ctx.cwd, name, candidate);
|
|
79
|
+
ctx.ui.notify(`Candidate retained, not adopted. Comparison must bind configuration digest ${workPolicyDigest(candidate)} to actual outputs. Use Learning to review full artifacts, record quality and choose adopt/reject/defer.`, "info"); return;
|
|
80
|
+
}
|
|
81
|
+
const view = workspace.inspect(Date.now()), comparisons = view.comparisons.filter(c => c.state !== "deferred");
|
|
82
|
+
if(!comparisons.length)throw Error("Adoption deferred: no ready retained comparison. Open Learning to connect/review actual evidence and inspect defer reasons. No setting was activated.");
|
|
83
|
+
const labels = comparisons.map((c, i) => `${i + 1}. ${c.title}`), picked = await ctx.ui.select("Retained comparison", labels), comparison = comparisons[labels.indexOf(picked ?? "")]; if (!comparison) return;
|
|
84
|
+
if (choice === menu[1]) {
|
|
85
|
+
let adoptionBinding = workspace.comparisonContext(comparison.name).adoptionBinding;
|
|
86
|
+
if (!adoptionBinding) {
|
|
87
|
+
const files=await readdir(join(ctx.cwd,".pi","work-policies")); if(files.length>128)throw Error("candidate profile bound exceeded");
|
|
88
|
+
const candidates: {name:string;policy:WorkPolicy}[]=[];
|
|
89
|
+
for(const file of files.filter(f=>/^[a-f0-9]{64}\.json$/.test(f))){const saved=await readProductJson(join(ctx.cwd,".pi","work-policies",file)) as {name:string;policy:WorkPolicy};const policy=await readPolicy(ctx.cwd,file.slice(0,-5));if(policy.scopeDigest===current.scopeDigest)candidates.push({name:saved.name,policy});}
|
|
90
|
+
const names=candidates.map((c,i)=>`${i+1}. ${c.name}: ${c.policy.profiles.map(p=>`${p.model}/${p.thinking}`).join(", ")}`),picked=await ctx.ui.select("Candidate already compared in this retained evidence",names),selected=candidates[names.indexOf(picked??"")];if(!selected)return;
|
|
91
|
+
if(!await ctx.ui.confirm("Bind this scoped adoption proposal?","This requires linked confirmed cases, hypothesis and a durable full-artifact choice of this exact candidate. It does not create eligibility or activate anything."))return;
|
|
92
|
+
adoptionBinding=bindLearningAdoption(workspace,comparison.name,{candidateDigest:workPolicyDigest(selected.policy),rollbackCandidateDigest:current.candidateDigest,assessmentPolicyDigest:selected.policy.assessmentPolicyDigest,expiresAt:Date.now()+7*86400000});
|
|
93
|
+
}
|
|
94
|
+
const candidate = await readPolicy(ctx.cwd, adoptionBinding.candidateDigest), facts = await independentFacts(ctx, adoptionBinding); if (!facts) return;
|
|
95
|
+
const a = authority(binding.initial.authorityId, adoptionBinding, facts), receipt = workspace.prepareAdoption(comparison.name, a.adoption, facts, Date.now());
|
|
96
|
+
const request: WorkPolicyActivation = { version: "ordinary-work-activation-v1", requestId: `activate-${randomUUID()}`, expectedRevision: current.revision, expectedCandidateDigest: current.candidateDigest, candidate, binding: adoptionBinding, receipt };
|
|
97
|
+
if (!await ctx.ui.confirm("Activate for NEXT orders only?", `${comparison.title}\n${candidate.profiles.map(p => `${p.taskId}: ${p.model} / ${p.thinking}`).join("\n")}\nNo active work changes. This is separate from your quality choice.`)) return;
|
|
98
|
+
a.activationDigests = [workPolicyActivationDigest(request)];
|
|
99
|
+
const applied = await registry.activate(request, a), archiveRoot = workspace.configuration().archiveRoot;
|
|
100
|
+
const registryManifestId = retain(harness, archiveRoot, "producer-registry", applied);
|
|
101
|
+
const wrapper = retain(harness, archiveRoot, "learning-registry-receipt", { version: "learning-registry-receipt-v1", operation: "activate", requestId: request.requestId, adoptionId: receipt.id, scopeDigest: applied.scopeDigest, candidateDigest: applied.candidateDigest, revision: applied.revision, registryManifestId });
|
|
102
|
+
try { workspace.linkActivation(comparison.name, wrapper, [wrapper]); }
|
|
103
|
+
catch (error) { throw Error(`Registry activated but learning link failed (${String(error)}). Do not activate again; use Recover learning link. Retained receipt ${wrapper}.`); }
|
|
104
|
+
ctx.ui.notify("Activated for subsequent bounded work runs. Existing runs remain pinned; later outcomes are still unobserved.", "info"); return;
|
|
105
|
+
}
|
|
106
|
+
if(choice===menu[4]){
|
|
107
|
+
const change=current.lastChange,receipt=workspace.preparedAdoption(comparison.name);
|
|
108
|
+
if(!change||!receipt||change.adoptionId!==receipt.id)throw Error("Last original registry change does not belong to this comparison");
|
|
109
|
+
if(!await ctx.ui.confirm("Reconnect actual registry observation?",`The last ${change.operation} is already applied at revision ${current.revision}. This only retains and links that exact original registry observation; no effect is replayed.`))return;
|
|
110
|
+
const root=workspace.configuration().archiveRoot,registryManifestId=retain(harness,root,"producer-registry",current),wrapper=retain(harness,root,"learning-registry-receipt",{version:"learning-registry-receipt-v1",operation:change.operation,requestId:change.requestId,adoptionId:receipt.id,scopeDigest:current.scopeDigest,candidateDigest:current.candidateDigest,revision:current.revision,registryManifestId});
|
|
111
|
+
if(change.operation==="activate")workspace.linkActivation(comparison.name,wrapper,[wrapper]);else workspace.linkRollback(comparison.name,wrapper,[wrapper]);
|
|
112
|
+
ctx.ui.notify("Original registry observation linked. No activation or rollback replayed.","info");return;
|
|
113
|
+
}
|
|
114
|
+
if (!current.activation) throw Error("No current adoption to roll back");
|
|
115
|
+
const receipt = workspace.preparedAdoption(comparison.name);
|
|
116
|
+
if (!receipt || receipt.id !== current.activation.receipt.id) throw Error("Selected comparison is not the active adoption");
|
|
117
|
+
const root = workspace.configuration().archiveRoot;
|
|
118
|
+
const evidence = retain(harness, root, "producer-rollback-request", { reason: "operator-request", adoptionId: receipt.id, observedRevision: current.revision });
|
|
119
|
+
const request = workspace.previewRollback(comparison.name, "operator-request", [evidence], Date.now() + 120_000);
|
|
120
|
+
const restore = await registry.previewRollback(request);
|
|
121
|
+
if (!await ctx.ui.confirm("Roll back NEXT orders?", `Restore candidate: ${restore.restoreCandidateDigest}\n${restore.candidate.profiles.map(p => `${p.taskId}: ${p.model} / ${p.thinking}`).join("\n")}\nNo active run changes; no defect or improvement is inferred.`)) return;
|
|
122
|
+
const a = authority(binding.initial.authorityId); a.adoption = { id: a.id, adoptions: [], rollbacks: [request.id] };
|
|
123
|
+
workspace.prepareRollback(comparison.name, request, a.adoption, Date.now(), { adoptionId: receipt.id, candidateDigest: current.candidateDigest, scopeDigest: current.scopeDigest });
|
|
124
|
+
const applied = await registry.rollback(request, a), registryManifestId = retain(harness, root, "producer-registry", applied);
|
|
125
|
+
const wrapper = retain(harness, root, "learning-registry-receipt", { version: "learning-registry-receipt-v1", operation: "rollback", requestId: request.id, adoptionId: receipt.id, scopeDigest: applied.scopeDigest, candidateDigest: applied.candidateDigest, revision: applied.revision, registryManifestId });
|
|
126
|
+
try { workspace.linkRollback(comparison.name, wrapper, [wrapper]); }
|
|
127
|
+
catch (error) { throw Error(`Rollback applied but learning link failed (${String(error)}). Use Recover learning link; do not repeat the effect. Retained receipt ${wrapper}.`); }
|
|
128
|
+
ctx.ui.notify("Rollback applied for next orders. Active/history-bearing runs were not changed.", "info");
|
|
129
|
+
}
|
|
130
|
+
/** Fresh human facts at use; a stored lifecycle/receipt is never treated as independent live authority. */
|
|
131
|
+
export async function prepareNextWorkPolicy(ctx: ExtensionCommandContext, state: DeclaredWorkState, setup: WorkSetup) {
|
|
132
|
+
const binding = await loadWorkPolicyRegistry(ctx.cwd, state); if (!binding) return { setup, pin: async (_id: string) => null };
|
|
133
|
+
const registry = openWorkPolicyRegistry(binding), current = await registry.inspect();
|
|
134
|
+
const facts = current.activation ? await independentFacts(ctx, current.activation.binding) : undefined;
|
|
135
|
+
if (facts === null) throw Error("Next-order adoption deferred; no fallback profile or child launched");
|
|
136
|
+
const a = authority(binding.initial.authorityId, current.activation?.binding, facts);
|
|
137
|
+
const configured = { ...setup, tasks: setup.tasks.map(t => { const profile = current.candidate.profiles.find(p => p.taskId === t.id); if (!profile || profile.agent !== t.agent) throw Error("adopted profile no longer matches task definition"); return { ...t, model: profile.model, thinking: profile.thinking }; }) };
|
|
138
|
+
return { setup: configured, async pin(orderId: string) { const pinned = await registry.pin(orderId, a, { revision: current.revision, candidateDigest: current.candidateDigest }); if (pinned.candidateDigest !== current.candidateDigest || pinned.revision !== current.revision) throw Error("registry changed before order pin; no child launched"); return { orderId, candidateDigest: pinned.candidateDigest, adoptionId: pinned.adoptionId, revision: pinned.revision, scopeDigest: binding.initial.scopeDigest }; } };
|
|
139
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { mkdir } from "node:fs/promises";
|
|
5
|
+
import { BorderedLoader, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { supportedModelEfforts as getSupportedThinkingLevels } from "../src/model-preflight.ts";
|
|
7
|
+
import { splitBudget } from "../src/fanout.ts";
|
|
8
|
+
import { runWorkSetup, type WorkRunResult } from "../src/work-run.ts";
|
|
9
|
+
import { loadWorkSetup, type RecordedWorkSetup } from "../src/work-setup.ts";
|
|
10
|
+
import { privateDirectory, writeProductJson } from "../src/product-files.ts";
|
|
11
|
+
import { loadDeclaredWork } from "../src/work-command.ts";
|
|
12
|
+
import { readDailySnapshot } from "../src/daily-view-input.ts";
|
|
13
|
+
import { ordinaryChildrenFor } from "../src/ordinary-children.ts";
|
|
14
|
+
import { runOneDelegation } from "./run-delegation.ts";
|
|
15
|
+
import { newDelegationOccurrence } from "./execution-occurrence.ts";
|
|
16
|
+
import { assertDelegationAuthority } from "./delegation-authority.ts";
|
|
17
|
+
import type { GrantsSession } from "./session.ts";
|
|
18
|
+
import { prepareNextWorkPolicy } from "./work-policy-session.ts";
|
|
19
|
+
|
|
20
|
+
export async function runSelectedWork(session: GrantsSession, ctx: ExtensionCommandContext, setup: RecordedWorkSetup, priorities?: string[], lifetime?: { signal: AbortSignal; started: (promise: Promise<WorkRunResult>) => void }): Promise<WorkRunResult | null> {
|
|
21
|
+
assertDelegationAuthority(session);
|
|
22
|
+
if (!ctx.isIdle() || !ordinaryChildrenFor(session).quiescent()) throw Error("Wait for original work to settle before starting a bounded run");
|
|
23
|
+
const loaded = await loadWorkSetup(setup.state);
|
|
24
|
+
if (!loaded || session.declaredWork?.selectedSnapshot.snapshot.digest !== setup.state.selectedSnapshot.snapshot.digest) throw Error("selected work changed");
|
|
25
|
+
const available=splitBudget(session.fanoutBudget,setup.setup.tasks.length);if(!available.ok)throw Error(available.reason);
|
|
26
|
+
const policy = await prepareNextWorkPolicy(ctx, setup.state, setup.setup), configured = policy.setup;
|
|
27
|
+
// Resolve every profile before any ledger, result store or child. No provider/model/effort fallback.
|
|
28
|
+
for (const task of configured.tasks) {
|
|
29
|
+
const slash = task.model.indexOf("/"), model = ctx.modelRegistry.find(task.model.slice(0, slash), task.model.slice(slash + 1));
|
|
30
|
+
if (!model || !getSupportedThinkingLevels(model).includes(task.thinking)) throw Error(`Unsupported profile for ${task.outcome}: ${task.model} / ${task.thinking}; choose a listed model and effort`);
|
|
31
|
+
}
|
|
32
|
+
if (!await ctx.ui.confirm("Run this work?", `${setup.setup.tasks.length} attempts; at most ${setup.setup.maxParallel} parallel. Each child's existing timeout/output/grant bounds apply. Dependencies receive complete bounded predecessor output. No automatic retries; no universal token/cost cap on ordinary children.\n\n${configured.tasks.map(t => `${t.outcome} — ${t.agent ?? "no tools"}, ${t.model}, ${t.thinking}`).join("\n")}`)) return null;
|
|
33
|
+
const selectedNow=await loadDeclaredWork(setup.state.statePath);
|
|
34
|
+
if(selectedNow?.selectedSnapshot.snapshot.digest!==setup.state.selectedSnapshot.snapshot.digest||session.declaredWork?.selectedSnapshot.snapshot.digest!==setup.state.selectedSnapshot.snapshot.digest)throw Error("work selection changed during confirmation; no order started");
|
|
35
|
+
const root = join(homedir(), ".local", "state", "pi-daddy", "work-runs");
|
|
36
|
+
await mkdir(root, { recursive: true, mode: 0o700 }); await privateDirectory(root);
|
|
37
|
+
const abort = new AbortController(), signal = lifetime ? AbortSignal.any([abort.signal, lifetime.signal]) : abort.signal;
|
|
38
|
+
signal.throwIfAborted(); const orderId = randomUUID(), policyPin = await policy.pin(orderId);
|
|
39
|
+
const run = (update: (text: string) => void) => { const pending = runWorkSetup({ directory: join(root, orderId), orderId, policyPin, selectionDigest: setup.state.selectedSnapshot.snapshot.digest, setup: configured, budget: session.fanoutBudget, priorities, signal, admissionOpen:()=>(ordinaryChildrenFor(session).inspect() as {admission:string}).admission==="open",
|
|
40
|
+
onUpdate: rows => update(rows.map(row => `${row.state}: ${setup.setup.tasks.find(t => t.id === row.id)!.outcome}`).join("\n")),
|
|
41
|
+
execute: async (task, prompt, budget, started) => {
|
|
42
|
+
assertDelegationAuthority(session);
|
|
43
|
+
if(session.declaredWork?.selectedSnapshot.snapshot.digest!==setup.state.selectedSnapshot.snapshot.digest)throw Error("selected work changed; remaining order attempts were not launched");
|
|
44
|
+
const ids = newDelegationOccurrence(session, setup.setup.tasks.findIndex(t => t.id === task.id));
|
|
45
|
+
await started(ids.executionId);
|
|
46
|
+
const state = { ...setup.state, obligation: setup.tasks.find(t => t.id === task.id)!.obligation };
|
|
47
|
+
return runOneDelegation(session, { task: prompt, ...(task.agent ? { agent: task.agent } : { tools: [] }), model: task.model, thinking: task.thinking, correlation: { schema_version: "1.0", task_id: task.id, context_id: `work-${setup.setup.id}` } }, ids, budget, ctx, signal, { declaredWork: state, toolCallId: `work-run:${ids.executionId}` });
|
|
48
|
+
},
|
|
49
|
+
}); lifetime?.started(pending); return pending; };
|
|
50
|
+
let result: WorkRunResult;
|
|
51
|
+
if (ctx.mode === "tui") {
|
|
52
|
+
result = await ctx.ui.custom<WorkRunResult>((tui, theme, _keys, done) => {
|
|
53
|
+
const loader = new BorderedLoader(tui, theme, "Running declared work — Esc requests cancellation; awaiting all original children");
|
|
54
|
+
loader.onAbort = () => abort.abort();
|
|
55
|
+
void run(text => ctx.ui.setWidget("pi-daddy-work", text.split("\n"))).then(done).catch(error => done({ error } as unknown as WorkRunResult));
|
|
56
|
+
return loader;
|
|
57
|
+
});
|
|
58
|
+
ctx.ui.setWidget("pi-daddy-work", undefined);
|
|
59
|
+
if ("error" in result) throw (result as unknown as { error: unknown }).error;
|
|
60
|
+
} else result = await run(text => ctx.ui.notify(text, "info"));
|
|
61
|
+
// Navigation index only; the original occurrence ledger/control journal remains the result authority.
|
|
62
|
+
await writeProductJson(join(session.cwd, ".pi", "work-last-run.json"), result.binding, true);
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
export async function showWorkResults(ctx: ExtensionCommandContext, result: WorkRunResult): Promise<void> {
|
|
66
|
+
const choices = result.tasks.map((row, i) => `${i + 1}. ${row.state} — ${result.binding.initial.setup.tasks.find(t => t.id === row.id)?.outcome ?? row.id}`);
|
|
67
|
+
const choice = await ctx.ui.select("Results — execution is not acceptance", choices);
|
|
68
|
+
const row = result.tasks[choices.indexOf(choice ?? "")]; if (!row) return;
|
|
69
|
+
if (!row.resultPath || !row.resultDigest) { ctx.ui.notify(row.reason ?? "No retained output; original acknowledgement unavailable", "warning"); return; }
|
|
70
|
+
if (row.resultPath !== join(result.binding.directory, `${row.id}.txt`)) throw Error("result path mismatch");
|
|
71
|
+
const source = await readDailySnapshot(row.resultPath, 1024 * 1024);
|
|
72
|
+
if (source.status !== "read" || source.sha256 !== row.resultDigest) throw Error("retained output missing or changed");
|
|
73
|
+
const output = new TextDecoder("utf8", { fatal: true }).decode(source.bytes);
|
|
74
|
+
await ctx.ui.editor("Retained full output (controls escaped; edits do not alter the artifact)", output.replace(/[\p{Cc}\p{Cf}]/gu, c => c === "\n" || c === "\t" ? c : `\\u${c.charCodeAt(0).toString(16).padStart(4,"0")}`));
|
|
75
|
+
}
|
|
@@ -11,12 +11,12 @@ export async function beginDeclaredWorkAttempt(input: {
|
|
|
11
11
|
childId: string;
|
|
12
12
|
executionId: string;
|
|
13
13
|
parentExecutionId: string | null;
|
|
14
|
-
toolCallId?: string;
|
|
14
|
+
toolCallId?: string; declaredWork?: GrantsSession["declaredWork"];
|
|
15
15
|
preparedWorkspace?: PreparedWorkspace;
|
|
16
16
|
configuredTimeoutMs: number;
|
|
17
17
|
startedAt: Date;
|
|
18
18
|
}): Promise<null | { finish(state: Extract<WorkOccurrencePayload["state"], "completed" | "failed">): Promise<void> }> {
|
|
19
|
-
const state = input.session.declaredWork;
|
|
19
|
+
const state = input.declaredWork ?? input.session.declaredWork;
|
|
20
20
|
if (!state) return null;
|
|
21
21
|
const argument = (flag: string): string | null => {
|
|
22
22
|
const index = input.plan.args.indexOf(flag);
|