pi-daddy 0.49.5 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/CHANGELOG.md +51 -1
  2. package/README.md +217 -27
  3. package/dist/governance/initiative-coordinator.d.ts +58 -0
  4. package/dist/governance/initiative-coordinator.d.ts.map +1 -0
  5. package/dist/governance/initiative-coordinator.js +348 -0
  6. package/dist/governance/initiative-coordinator.js.map +1 -0
  7. package/dist/governance/initiative-effects.d.ts +20 -0
  8. package/dist/governance/initiative-effects.d.ts.map +1 -0
  9. package/dist/governance/initiative-effects.js +108 -0
  10. package/dist/governance/initiative-effects.js.map +1 -0
  11. package/dist/governance/initiative-state.d.ts +13 -0
  12. package/dist/governance/initiative-state.d.ts.map +1 -0
  13. package/dist/governance/initiative-state.js +122 -0
  14. package/dist/governance/initiative-state.js.map +1 -0
  15. package/dist/governance/operation-artifact-io.d.ts +8 -0
  16. package/dist/governance/operation-artifact-io.d.ts.map +1 -0
  17. package/dist/governance/operation-artifact-io.js +95 -0
  18. package/dist/governance/operation-artifact-io.js.map +1 -0
  19. package/dist/governance/operation-artifact-scan.d.ts +13 -0
  20. package/dist/governance/operation-artifact-scan.d.ts.map +1 -0
  21. package/dist/governance/operation-artifact-scan.js +71 -0
  22. package/dist/governance/operation-artifact-scan.js.map +1 -0
  23. package/dist/governance/operation-artifacts.d.ts +53 -0
  24. package/dist/governance/operation-artifacts.d.ts.map +1 -0
  25. package/dist/governance/operation-artifacts.js +309 -0
  26. package/dist/governance/operation-artifacts.js.map +1 -0
  27. package/dist/governance/runtime-settlement.d.ts +2 -0
  28. package/dist/governance/runtime-settlement.d.ts.map +1 -1
  29. package/dist/governance/runtime-settlement.js +26 -0
  30. package/dist/governance/runtime-settlement.js.map +1 -1
  31. package/dist/governance/workspace-acceptance.d.ts +5 -0
  32. package/dist/governance/workspace-acceptance.d.ts.map +1 -1
  33. package/dist/governance/workspace-acceptance.js +16 -0
  34. package/dist/governance/workspace-acceptance.js.map +1 -1
  35. package/dist/index.d.ts +8 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +8 -0
  38. package/dist/index.js.map +1 -1
  39. package/dist/kernel/dashboard-observation.d.ts +76 -0
  40. package/dist/kernel/dashboard-observation.d.ts.map +1 -0
  41. package/dist/kernel/dashboard-observation.js +49 -0
  42. package/dist/kernel/dashboard-observation.js.map +1 -0
  43. package/dist/kernel/dispatch-operation.d.ts +2 -0
  44. package/dist/kernel/dispatch-operation.d.ts.map +1 -1
  45. package/dist/kernel/dispatch-operation.js.map +1 -1
  46. package/dist/kernel/initiative.d.ts +94 -0
  47. package/dist/kernel/initiative.d.ts.map +1 -0
  48. package/dist/kernel/initiative.js +38 -0
  49. package/dist/kernel/initiative.js.map +1 -0
  50. package/dist/kernel/operation-artifact.d.ts +49 -0
  51. package/dist/kernel/operation-artifact.d.ts.map +1 -0
  52. package/dist/kernel/operation-artifact.js +4 -0
  53. package/dist/kernel/operation-artifact.js.map +1 -0
  54. package/dist/kernel/principal-binding.d.ts +4 -0
  55. package/dist/kernel/principal-binding.d.ts.map +1 -0
  56. package/dist/kernel/principal-binding.js +94 -0
  57. package/dist/kernel/principal-binding.js.map +1 -0
  58. package/dist/kernel/project-paths.d.ts +6 -0
  59. package/dist/kernel/project-paths.d.ts.map +1 -1
  60. package/dist/kernel/project-paths.js +12 -0
  61. package/dist/kernel/project-paths.js.map +1 -1
  62. package/dist/kernel/selected-definitions.d.ts.map +1 -1
  63. package/dist/kernel/selected-definitions.js +5 -91
  64. package/dist/kernel/selected-definitions.js.map +1 -1
  65. package/dist/kernel/workspace-diagnostics.d.ts +24 -0
  66. package/dist/kernel/workspace-diagnostics.d.ts.map +1 -0
  67. package/dist/kernel/workspace-diagnostics.js +81 -0
  68. package/dist/kernel/workspace-diagnostics.js.map +1 -0
  69. package/dist/products/activity-storage.d.ts +2 -0
  70. package/dist/products/activity-storage.d.ts.map +1 -0
  71. package/dist/products/activity-storage.js +119 -0
  72. package/dist/products/activity-storage.js.map +1 -0
  73. package/dist/products/activity-timeline.d.ts +4 -0
  74. package/dist/products/activity-timeline.d.ts.map +1 -1
  75. package/dist/products/activity-timeline.js +12 -0
  76. package/dist/products/activity-timeline.js.map +1 -1
  77. package/dist/products/dashboard-cli.d.ts +2 -0
  78. package/dist/products/dashboard-cli.d.ts.map +1 -1
  79. package/dist/products/dashboard-cli.js +41 -9
  80. package/dist/products/dashboard-cli.js.map +1 -1
  81. package/dist/products/dashboard-display-controls.d.ts.map +1 -1
  82. package/dist/products/dashboard-display-controls.js +30 -0
  83. package/dist/products/dashboard-display-controls.js.map +1 -1
  84. package/dist/products/dashboard-file-cache.d.ts +10 -0
  85. package/dist/products/dashboard-file-cache.d.ts.map +1 -0
  86. package/dist/products/dashboard-file-cache.js +38 -0
  87. package/dist/products/dashboard-file-cache.js.map +1 -0
  88. package/dist/products/dashboard-panels.d.ts +6 -0
  89. package/dist/products/dashboard-panels.d.ts.map +1 -0
  90. package/dist/products/dashboard-panels.js +179 -0
  91. package/dist/products/dashboard-panels.js.map +1 -0
  92. package/dist/products/dashboard-screen.d.ts +8 -0
  93. package/dist/products/dashboard-screen.d.ts.map +1 -1
  94. package/dist/products/dashboard-screen.js +86 -15
  95. package/dist/products/dashboard-screen.js.map +1 -1
  96. package/dist/products/dashboard-session-client.d.ts +16 -2
  97. package/dist/products/dashboard-session-client.d.ts.map +1 -1
  98. package/dist/products/dashboard-session-client.js +64 -11
  99. package/dist/products/dashboard-session-client.js.map +1 -1
  100. package/dist/products/dashboard-settings.d.ts.map +1 -1
  101. package/dist/products/dashboard-settings.js +4 -6
  102. package/dist/products/dashboard-settings.js.map +1 -1
  103. package/dist/products/ecosystem-versions.d.ts +1 -1
  104. package/dist/products/ecosystem-versions.d.ts.map +1 -1
  105. package/extensions/activity-timeline.ts +3 -1
  106. package/extensions/artifact-bridge.ts +130 -0
  107. package/extensions/dashboard-live.ts +63 -0
  108. package/extensions/dashboard-observation.ts +39 -0
  109. package/extensions/dashboard-session-server.ts +45 -3
  110. package/extensions/dashboard-sources.ts +124 -0
  111. package/extensions/delegation-artifacts.ts +125 -0
  112. package/extensions/delegation-operations.ts +42 -13
  113. package/extensions/ecosystem-versions.ts +12 -5
  114. package/extensions/grants-command.ts +34 -6
  115. package/extensions/grants.ts +9 -20
  116. package/extensions/initiative-dashboard.ts +143 -0
  117. package/extensions/initiative-runtime.ts +406 -0
  118. package/extensions/runtime-snapshot.ts +118 -2
  119. package/extensions/session-environment.ts +13 -1
  120. package/extensions/session.ts +28 -10
  121. package/extensions/workspace-diagnostics.ts +90 -0
  122. package/package.json +1 -1
  123. package/src/governance/initiative-coordinator.ts +400 -0
  124. package/src/governance/initiative-effects.ts +146 -0
  125. package/src/governance/initiative-state.ts +144 -0
  126. package/src/governance/operation-artifact-io.ts +103 -0
  127. package/src/governance/operation-artifact-scan.ts +77 -0
  128. package/src/governance/operation-artifacts.ts +363 -0
  129. package/src/governance/runtime-settlement.ts +28 -0
  130. package/src/governance/workspace-acceptance.ts +18 -0
  131. package/src/index.ts +13 -0
  132. package/src/kernel/dashboard-observation.ts +109 -0
  133. package/src/kernel/dispatch-operation.ts +2 -0
  134. package/src/kernel/initiative.ts +126 -0
  135. package/src/kernel/operation-artifact.ts +46 -0
  136. package/src/kernel/principal-binding.ts +104 -0
  137. package/src/kernel/project-paths.ts +16 -0
  138. package/src/kernel/selected-definitions.ts +5 -100
  139. package/src/kernel/workspace-diagnostics.ts +110 -0
  140. package/src/products/activity-storage.ts +128 -0
  141. package/src/products/activity-timeline.ts +11 -0
  142. package/src/products/dashboard-cli.ts +44 -9
  143. package/src/products/dashboard-display-controls.ts +27 -0
  144. package/src/products/dashboard-file-cache.ts +38 -0
  145. package/src/products/dashboard-panels.ts +217 -0
  146. package/src/products/dashboard-screen.ts +107 -17
  147. package/src/products/dashboard-session-client.ts +78 -14
  148. package/src/products/dashboard-settings.ts +4 -6
  149. package/src/products/ecosystem-versions.ts +2 -1
@@ -0,0 +1,46 @@
1
+ /** Exact producer evidence. Retention is neither live authority nor semantic acceptance. */
2
+ import type { OperationReference, OperationRequest } from "./dispatch-operation.ts";
3
+ export const OPERATION_ARTIFACT_VERSION = 1;
4
+ export const MAX_OPERATION_ARTIFACT_BYTES = 4 * 1024 * 1024;
5
+ export const MAX_OPERATION_MANIFEST_BYTES = 64 * 1024;
6
+ export interface OperationArtifactOwner {
7
+ sessionId: string;
8
+ cwd: string;
9
+ }
10
+ export interface OperationArtifactContent {
11
+ path: string;
12
+ sha256: string;
13
+ bytes: number;
14
+ }
15
+ export interface OperationArtifactRef {
16
+ version: 1;
17
+ producer: "pi-daddy";
18
+ owner: OperationArtifactOwner;
19
+ operationId: string;
20
+ executionId: string;
21
+ manifest: OperationArtifactContent;
22
+ }
23
+ export interface RetainedOperationFinal {
24
+ state: "complete";
25
+ text: string;
26
+ sessionId: string;
27
+ messageId: string;
28
+ leafId: string;
29
+ sha256: string;
30
+ }
31
+ export interface OperationArtifactManifest {
32
+ version: 1;
33
+ producer: "pi-daddy";
34
+ owner: OperationArtifactOwner;
35
+ request: OperationRequest;
36
+ operation: Omit<OperationReference, "artifact">;
37
+ observedAt: string;
38
+ final?: Omit<RetainedOperationFinal, "text"> & { content: OperationArtifactContent };
39
+ partial?: OperationArtifactContent;
40
+ }
41
+ export interface OperationArtifactOutcome {
42
+ operation: Omit<OperationReference, "artifact">;
43
+ final?: RetainedOperationFinal;
44
+ /** Available visible output only; never promoted to an exact native final. */
45
+ partial?: string;
46
+ }
@@ -0,0 +1,104 @@
1
+ /** Legacy Principal dual-definition binding. Ordinary selected inline roles do not need this adapter. */
2
+ import { createHash } from "node:crypto";
3
+ import { dirname, join } from "node:path";
4
+ import { realpath } from "node:fs/promises";
5
+ import { ceilingForDefinition, parseSkillDefinition, type SkillDefinition } from "./definitions.ts";
6
+ import { resolve } from "./resolve.ts";
7
+ import type { DefinitionSource } from "./definition-sources.ts";
8
+ const requiredPhases = ["plan", "build", "review", "debug", "investigate"];
9
+ const phases = [...requiredPhases, "test-review"];
10
+ const hash = (value: string) => createHash("sha256").update(value, "utf8").digest("hex");
11
+ const object = (x: unknown): x is Record<string, unknown> => !!x && typeof x === "object" && !Array.isArray(x);
12
+ const exact = (x: Record<string, unknown>, keys: string[]) =>
13
+ Object.keys(x).sort().join(",") === [...keys].sort().join(",");
14
+ export async function principalBinding(
15
+ path: string,
16
+ inline: SkillDefinition,
17
+ skillText: string,
18
+ sources: DefinitionSource[] | undefined,
19
+ read: (path: string, kind: DefinitionSource["kind"], sources?: DefinitionSource[]) => Promise<string>,
20
+ ): Promise<SkillDefinition> {
21
+ const phase = inline.name;
22
+ const marked = inline.metadata?.["principal-package"] === "principal-pi-skills";
23
+ if (!phases.includes(phase) || path !== join(dirname(dirname(path)), phase, "SKILL.md")) {
24
+ if (marked) throw Error("marked Principal skill has a noncanonical phase or path");
25
+ return inline;
26
+ }
27
+ const root = dirname(dirname(path));
28
+ let packageText: string;
29
+ try {
30
+ packageText = await read(join(root, "package.json"), "package", sources);
31
+ } catch (error) {
32
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && !marked) return inline;
33
+ throw error;
34
+ }
35
+ const pkg: unknown = JSON.parse(packageText);
36
+ if (!object(pkg) || pkg.name !== "principal-pi-skills") {
37
+ if (marked) throw Error("marked Principal skill has missing or wrong package identity");
38
+ return inline;
39
+ }
40
+ const manifest: unknown = JSON.parse(await read(join(root, "principal-agents.json"), "binding-manifest", sources));
41
+ if (
42
+ !object(manifest) ||
43
+ !exact(manifest, ["version", "package", "bindings"]) ||
44
+ manifest.version !== 1 ||
45
+ manifest.package !== "principal-pi-skills" ||
46
+ !object(manifest.bindings) ||
47
+ !exact(manifest.bindings, Object.hasOwn(manifest.bindings, "test-review") ? phases : requiredPhases)
48
+ )
49
+ throw Error("invalid Principal binding manifest");
50
+ for (const name of Object.keys(manifest.bindings)) {
51
+ const row = manifest.bindings[name];
52
+ if (
53
+ !object(row) ||
54
+ !exact(row, ["skill", "agent", "skillSha256", "agentSha256"]) ||
55
+ row.skill !== `${name}/SKILL.md` ||
56
+ row.agent !== `agents/principal-${name}.md` ||
57
+ typeof row.skillSha256 !== "string" ||
58
+ !/^[a-f0-9]{64}$/.test(row.skillSha256) ||
59
+ typeof row.agentSha256 !== "string" ||
60
+ !/^[a-f0-9]{64}$/.test(row.agentSha256)
61
+ )
62
+ throw Error("invalid Principal binding row");
63
+ }
64
+ if (!Object.hasOwn(manifest.bindings, phase)) throw Error("selected Principal phase has no binding row");
65
+ const row = manifest.bindings[phase] as Record<string, string>;
66
+ const agentPath = join(root, row.agent);
67
+ if (
68
+ (await realpath(agentPath)) !== join(await realpath(root), row.agent) ||
69
+ (await realpath(path)) !== join(await realpath(root), row.skill)
70
+ )
71
+ throw Error("Principal binding path escaped its selected package");
72
+ const agentText = await read(agentPath, "delegated-agent", sources);
73
+ if (hash(skillText) !== row.skillSha256 || hash(agentText) !== row.agentSha256)
74
+ throw Error("Principal binding hash mismatch");
75
+ const agent = parseSkillDefinition(agentPath, agentText);
76
+ if (!agent) throw Error("Principal delegated definition is malformed");
77
+ const inlineCeiling = ceilingForDefinition(inline),
78
+ delegatedCeiling = ceilingForDefinition(agent);
79
+ if (
80
+ inlineCeiling.undeclared ||
81
+ delegatedCeiling.undeclared ||
82
+ inlineCeiling.patterns.length ||
83
+ delegatedCeiling.patterns.length
84
+ )
85
+ throw Error("Principal binding needs two declared pattern-free ceilings");
86
+ const ceiling = resolve({
87
+ requested: delegatedCeiling.capabilities,
88
+ parentGrant: inlineCeiling.capabilities,
89
+ subsumption: false,
90
+ }).effective;
91
+ const header = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/.exec(agentText)!;
92
+ return {
93
+ ...agent,
94
+ name: phase,
95
+ source: agentPath,
96
+ sourceHash: hash(agentText),
97
+ selectedSkillHash: hash(skillText),
98
+ body: agentText.slice(header[0].length),
99
+ allowedTools: ceiling.join(","),
100
+ runtimePreferences: agent.runtimePreferences ?? inline.runtimePreferences,
101
+ ...(typeof pkg.version === "string" ? { packageVersion: pkg.version } : {}),
102
+ binding: Object.freeze({ package: "principal-pi-skills", phase }),
103
+ };
104
+ }
@@ -50,6 +50,15 @@ export const PROJECT_GITIGNORE_CONTENT = `# Written by pi-daddy init. Only setti
50
50
  !settings.json
51
51
  `;
52
52
 
53
+ /** Startup owns only these volatile paths. Preserve settings and unrelated project files. */
54
+ export const ACTIVITY_GITIGNORE_CONTENT = `# Pi Daddy volatile runtime files; settings.json remains reviewable.
55
+ /${PROJECT_FILES.activityTimeline}
56
+ /${PROJECT_FILES.activityTimeline}.lock
57
+ /content/
58
+ /${PROJECT_FILES.ledger}
59
+ /${PROJECT_FILES.ledger}.lock
60
+ `;
61
+
53
62
  /** Is this path inside pi's per-project directory of any project? The private controller journals refuse such paths. */
54
63
  export function isUnderPiProjectDir(path: string): boolean {
55
64
  return path.split(/[\\/]/).includes(PI_PROJECT_DIR);
@@ -107,3 +116,10 @@ export const legacyUserApprovalsPath = (cwd: string, env?: NodeJS.ProcessEnv) =>
107
116
  join(agentDir(env), "grants-approvals", projectFileName(cwd));
108
117
  export const legacyProjectLedgerPath = (cwd: string) => join(piProjectDir(cwd), "grants.jsonl");
109
118
  export const legacyGrantEnvPath = (cwd: string) => join(piProjectDir(cwd), "grants.env");
119
+
120
+ /** Private producer results, separate from optional execution diagnostics. */
121
+ export const operationArtifactsDir = (directory = agentDir()) =>
122
+ join(directory, PROJECT_STATE_DIRNAME, "operation-results");
123
+
124
+ /** One-host cooperative initiative ownership, separate from repository writer leases. */
125
+ export const initiativeStateDir = (directory = agentDir()) => join(directory, PROJECT_STATE_DIRNAME, "initiatives");
@@ -1,10 +1,10 @@
1
1
  /** Selected Pi 1.0.4 resources, frozen once per extension instance. No independent resource scan. */
2
2
  import { createHash } from "node:crypto";
3
- import { dirname, join, resolve as resolvePath } from "node:path";
4
- import { lstat, realpath } from "node:fs/promises";
3
+ import { resolve as resolvePath } from "node:path";
4
+ import { lstat } from "node:fs/promises";
5
5
  import { BoundedReadCleanupError, readBoundedBytes } from "./bounded-read.ts";
6
- import { ceilingForDefinition, parseSkillDefinition, type SkillDefinition } from "./definitions.ts";
7
- import { resolve } from "./resolve.ts";
6
+ import { parseSkillDefinition, type SkillDefinition } from "./definitions.ts";
7
+ import { principalBinding } from "./principal-binding.ts";
8
8
  import type { DefinitionSource } from "./definition-sources.ts";
9
9
  import type { CatalogEntry } from "./catalog.ts";
10
10
  export interface SelectedCommand {
@@ -12,12 +12,7 @@ export interface SelectedCommand {
12
12
  name: string;
13
13
  sourceInfo?: { path?: string };
14
14
  }
15
- const requiredPhases = ["plan", "build", "review", "debug", "investigate"];
16
- const phases = [...requiredPhases, "test-review"];
17
15
  const hash = (value: string) => createHash("sha256").update(value, "utf8").digest("hex");
18
- const object = (x: unknown): x is Record<string, unknown> => !!x && typeof x === "object" && !Array.isArray(x);
19
- const exact = (x: Record<string, unknown>, keys: string[]) =>
20
- Object.keys(x).sort().join(",") === [...keys].sort().join(",");
21
16
  async function read(path: string, kind: DefinitionSource["kind"], sources?: DefinitionSource[]): Promise<string> {
22
17
  if (!(await lstat(path)).isFile()) throw Error(`nonregular selected resource: ${path}`);
23
18
  const result = await readBoundedBytes(path, { maxBytes: 1024 * 1024, timeoutMs: 3000 });
@@ -26,96 +21,6 @@ async function read(path: string, kind: DefinitionSource["kind"], sources?: Defi
26
21
  sources?.push(Object.freeze({ kind, path, base64: result.bytes.toString("base64") }));
27
22
  return text;
28
23
  }
29
- async function principalBinding(
30
- path: string,
31
- inline: SkillDefinition,
32
- skillText: string,
33
- sources?: DefinitionSource[],
34
- ): Promise<SkillDefinition> {
35
- const phase = inline.name;
36
- const marked = inline.metadata?.["principal-package"] === "principal-pi-skills";
37
- if (!phases.includes(phase) || path !== join(dirname(dirname(path)), phase, "SKILL.md")) {
38
- if (marked) throw Error("marked Principal skill has a noncanonical phase or path");
39
- return inline;
40
- }
41
- const root = dirname(dirname(path));
42
- let packageText: string;
43
- try {
44
- packageText = await read(join(root, "package.json"), "package", sources);
45
- } catch (error) {
46
- if ((error as NodeJS.ErrnoException).code === "ENOENT" && !marked) return inline;
47
- throw error;
48
- }
49
- const pkg: unknown = JSON.parse(packageText);
50
- if (!object(pkg) || pkg.name !== "principal-pi-skills") {
51
- if (marked) throw Error("marked Principal skill has missing or wrong package identity");
52
- return inline;
53
- }
54
- const manifest: unknown = JSON.parse(await read(join(root, "principal-agents.json"), "binding-manifest", sources));
55
- if (
56
- !object(manifest) ||
57
- !exact(manifest, ["version", "package", "bindings"]) ||
58
- manifest.version !== 1 ||
59
- manifest.package !== "principal-pi-skills" ||
60
- !object(manifest.bindings) ||
61
- !exact(manifest.bindings, Object.hasOwn(manifest.bindings, "test-review") ? phases : requiredPhases)
62
- )
63
- throw Error("invalid Principal binding manifest");
64
- for (const name of Object.keys(manifest.bindings)) {
65
- const row = manifest.bindings[name];
66
- if (
67
- !object(row) ||
68
- !exact(row, ["skill", "agent", "skillSha256", "agentSha256"]) ||
69
- row.skill !== `${name}/SKILL.md` ||
70
- row.agent !== `agents/principal-${name}.md` ||
71
- typeof row.skillSha256 !== "string" ||
72
- !/^[a-f0-9]{64}$/.test(row.skillSha256) ||
73
- typeof row.agentSha256 !== "string" ||
74
- !/^[a-f0-9]{64}$/.test(row.agentSha256)
75
- )
76
- throw Error("invalid Principal binding row");
77
- }
78
- if (!Object.hasOwn(manifest.bindings, phase)) throw Error("selected Principal phase has no binding row");
79
- const row = manifest.bindings[phase] as Record<string, string>;
80
- const agentPath = join(root, row.agent);
81
- if (
82
- (await realpath(agentPath)) !== join(await realpath(root), row.agent) ||
83
- (await realpath(path)) !== join(await realpath(root), row.skill)
84
- )
85
- throw Error("Principal binding path escaped its selected package");
86
- const agentText = await read(agentPath, "delegated-agent", sources);
87
- if (hash(skillText) !== row.skillSha256 || hash(agentText) !== row.agentSha256)
88
- throw Error("Principal binding hash mismatch");
89
- const agent = parseSkillDefinition(agentPath, agentText);
90
- if (!agent) throw Error("Principal delegated definition is malformed");
91
- const inlineCeiling = ceilingForDefinition(inline),
92
- delegatedCeiling = ceilingForDefinition(agent);
93
- if (
94
- inlineCeiling.undeclared ||
95
- delegatedCeiling.undeclared ||
96
- inlineCeiling.patterns.length ||
97
- delegatedCeiling.patterns.length
98
- )
99
- throw Error("Principal binding needs two declared pattern-free ceilings");
100
- const ceiling = resolve({
101
- requested: delegatedCeiling.capabilities,
102
- parentGrant: inlineCeiling.capabilities,
103
- subsumption: false,
104
- }).effective;
105
- const header = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/.exec(agentText)!;
106
- return {
107
- ...agent,
108
- name: phase,
109
- source: agentPath,
110
- sourceHash: hash(agentText),
111
- selectedSkillHash: hash(skillText),
112
- body: agentText.slice(header[0].length),
113
- allowedTools: ceiling.join(","),
114
- runtimePreferences: agent.runtimePreferences ?? inline.runtimePreferences,
115
- ...(typeof pkg.version === "string" ? { packageVersion: pkg.version } : {}),
116
- binding: Object.freeze({ package: "principal-pi-skills", phase }),
117
- };
118
- }
119
24
  export async function selectedDefinitions(
120
25
  commands: readonly SelectedCommand[],
121
26
  captureSources = false,
@@ -144,7 +49,7 @@ export async function selectedDefinitions(
144
49
  const text = await read(path, "selected-skill", sources);
145
50
  const parsed = parseSkillDefinition(path, text);
146
51
  if (!parsed || parsed.name !== name) throw Error("selected name/path does not match definition");
147
- const bound = await principalBinding(path, parsed, text, sources);
52
+ const bound = await principalBinding(path, parsed, text, sources, read);
148
53
  const definitionId = hash(
149
54
  JSON.stringify({
150
55
  name,
@@ -0,0 +1,110 @@
1
+ /** Read-only routing observations. Reuse the dispatch owners; no lease, pin, acceptance or grant mutation. */
2
+ import { checkRoutingAuthority } from "./routing-authority.ts";
3
+ import { resolveWorkspace, type WorkspaceRegistryFile } from "./workspace.ts";
4
+ import type { Capability } from "./resolve.ts";
5
+ import type { WorkspacePins } from "./workspace-pin.ts";
6
+ import { GovernanceRefusal } from "./refusals.ts";
7
+
8
+ export interface WorkspaceRoutingObservation {
9
+ workspaceId: string;
10
+ state:
11
+ | "active"
12
+ | "pending-activation"
13
+ | "not-granted"
14
+ | "not-pinned"
15
+ | "not-registered"
16
+ | "destination-changed"
17
+ | "unavailable";
18
+ registered: boolean;
19
+ accepted: boolean | null;
20
+ capability: "held" | "missing";
21
+ pin: "matching" | "missing" | "moved" | "unchecked";
22
+ canonicalRoot?: string;
23
+ reason: string;
24
+ recovery: string;
25
+ dispatchChecks: string;
26
+ }
27
+ export async function inspectWorkspaceRouting(input: {
28
+ workspaceId: string;
29
+ registry: WorkspaceRegistryFile;
30
+ accepted: boolean | null;
31
+ ownGrant: readonly Capability[];
32
+ pins?: WorkspacePins;
33
+ depth: number;
34
+ }): Promise<WorkspaceRoutingObservation> {
35
+ const { workspaceId, registry, accepted } = input;
36
+ const authority = checkRoutingAuthority(workspaceId, input.ownGrant);
37
+ const registered = Object.hasOwn(registry.workspaces, workspaceId);
38
+ const pinned = input.pins?.has(workspaceId) ?? false;
39
+ const result: WorkspaceRoutingObservation = {
40
+ workspaceId,
41
+ registered,
42
+ accepted,
43
+ capability: authority ? "missing" : "held",
44
+ pin: pinned ? "unchecked" : "missing",
45
+ state: "unavailable",
46
+ reason: "Routing has not been checked.",
47
+ recovery: "Inspect the exact registered workspace.",
48
+ dispatchChecks:
49
+ "Observed routing only; candidate, selected task/input scope, approvals, lease and native settlement " +
50
+ "are checked by their owners at dispatch.",
51
+ };
52
+ if (!registered)
53
+ return {
54
+ ...result,
55
+ state: "not-registered",
56
+ reason: pinned
57
+ ? "This session pinned the ID, but its registry entry has been removed."
58
+ : "The ID is absent from the current registry.",
59
+ recovery:
60
+ "Review the registry with the operator. A remembered or removed ID does not authorize another directory.",
61
+ };
62
+ try {
63
+ const workspace = await resolveWorkspace(registry, workspaceId, { pins: input.pins ?? new Map() });
64
+ result.canonicalRoot = workspace.root;
65
+ result.pin = "matching";
66
+ } catch (error) {
67
+ if (!(error instanceof GovernanceRefusal)) throw error;
68
+ result.reason = error.message;
69
+ if (error.code === "WORKSPACE_NOT_AUTHORIZED" && typeof error.details?.resolved_root === "string") {
70
+ result.canonicalRoot = error.details.resolved_root;
71
+ if (pinned)
72
+ return {
73
+ ...result,
74
+ pin: "moved",
75
+ state: "destination-changed",
76
+ recovery:
77
+ "The registered destination differs from this owner's pin. Review the change; reload cannot repin and no session is started automatically.",
78
+ };
79
+ result.state = accepted === true && input.depth === 0 ? "pending-activation" : "not-pinned";
80
+ result.recovery =
81
+ input.depth > 0
82
+ ? "Ask the parent owner to select and grant the exact workspace. A descendant cannot mint its own pin."
83
+ : accepted === true
84
+ ? "Already accepted, but absent from this owner's settled pin. " +
85
+ "Use an explicitly selected new root session after reviewing its destination; reload keeps the old pin."
86
+ : "Review workspace acceptance with /grants workspaces. Acceptance applies to a new root session; reload does not create pins.";
87
+ } else {
88
+ result.recovery =
89
+ "Correct the reported registry or Git-worktree problem. Routing requires the exact worktree root, not a subdirectory.";
90
+ return result;
91
+ }
92
+ }
93
+ if (authority)
94
+ return {
95
+ ...result,
96
+ state: "not-granted",
97
+ reason: authority.reason,
98
+ recovery:
99
+ "This current grant lacks routing authority (never granted or revoked). " +
100
+ "The operator or parent must grant this exact ID; registration and acceptance do not grant it.",
101
+ };
102
+ if (result.pin !== "matching") return result;
103
+ return {
104
+ ...result,
105
+ state: "active",
106
+ reason: "The current capability and settled destination pin match a valid registered worktree.",
107
+ recovery:
108
+ "Reuse this workspace ID for the authorized operation. Dispatch still checks its current scope and execution prerequisites.",
109
+ };
110
+ }
@@ -0,0 +1,128 @@
1
+ /** Initialize default activity storage once per recorder, before observing product identity. */
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, realpath } from "node:fs/promises";
4
+ import { execFile } from "node:child_process";
5
+ import { promisify } from "node:util";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import {
8
+ ACTIVITY_GITIGNORE_CONTENT,
9
+ activityTimelinePath,
10
+ piProjectDir,
11
+ projectGitignorePath,
12
+ projectStateDir,
13
+ } from "../kernel/project-paths.ts";
14
+
15
+ const execute = promisify(execFile);
16
+ const missing = (error: unknown) => (error as NodeJS.ErrnoException).code === "ENOENT";
17
+
18
+ async function ordinaryDirectory(path: string): Promise<void> {
19
+ try {
20
+ await mkdir(path, { mode: 0o700 });
21
+ } catch (error) {
22
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
23
+ }
24
+ const info = await lstat(path);
25
+ if (!info.isDirectory() || info.isSymbolicLink())
26
+ throw Error("activity storage path is not an ordinary directory; nothing followed or replaced");
27
+ }
28
+
29
+ /** Without Git, allow ordinary non-repository roles but never guess that a marked repo is safe. */
30
+ async function markerFreeNonRepository(cwd: string): Promise<boolean> {
31
+ if (["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE"].some((key) => process.env[key]?.trim()))
32
+ return false;
33
+ let current = await realpath(cwd);
34
+ for (let depth = 0; depth < 128; depth++) {
35
+ try {
36
+ await lstat(join(current, ".git"));
37
+ return false;
38
+ } catch (error) {
39
+ if (!missing(error)) throw error;
40
+ }
41
+ const parent = dirname(current);
42
+ if (parent === current) return true;
43
+ current = parent;
44
+ }
45
+ return false;
46
+ }
47
+
48
+ export async function prepareDefaultActivityStorage(cwd: string, path: string): Promise<void> {
49
+ // Configured and transported locations retain their explicit existing policy.
50
+ if (resolve(path) !== activityTimelinePath(cwd)) return;
51
+ const root = resolve(cwd),
52
+ ignore = projectGitignorePath(root),
53
+ state = projectStateDir(root);
54
+ const git = (...args: string[]) =>
55
+ execute(
56
+ "git",
57
+ ["--no-optional-locks", ...(args[0] === "ls-files" ? ["--literal-pathspecs"] : []), "-C", root, ...args],
58
+ {
59
+ encoding: "utf8",
60
+ maxBuffer: 64 * 1024,
61
+ timeout: 2000,
62
+ env: { ...process.env, LC_ALL: "C" },
63
+ },
64
+ );
65
+ let repository = true;
66
+ try {
67
+ await git("rev-parse", "--show-toplevel");
68
+ } catch (error) {
69
+ const result = error as { code?: number | string; stderr?: string };
70
+ if (
71
+ (result.code === "ENOENT" || (result.code === 128 && result.stderr?.includes("not a git repository"))) &&
72
+ (await markerFreeNonRepository(root))
73
+ )
74
+ repository = false;
75
+ else throw Error("activity Git policy could not be checked; recording unavailable");
76
+ }
77
+ if (repository) {
78
+ const tracked = await git("ls-files", "-z", "--", path, `${path}.lock`, join(state, "content"));
79
+ if (tracked.stdout.length)
80
+ throw Error("activity runtime files are already tracked; no index or ignore policy was changed");
81
+ }
82
+ await ordinaryDirectory(piProjectDir(root));
83
+ await ordinaryDirectory(state);
84
+ let present = true;
85
+ try {
86
+ const info = await lstat(ignore);
87
+ if (!info.isFile() || info.isSymbolicLink())
88
+ throw Error("activity ignore path is not an ordinary file; nothing followed or replaced");
89
+ } catch (error) {
90
+ if (missing(error)) present = false;
91
+ else throw error;
92
+ }
93
+ if (!present) {
94
+ if (repository && (await git("ls-files", "-z", "--", ignore)).stdout.length)
95
+ throw Error("tracked ignore file is missing; recording did not recreate it");
96
+ try {
97
+ const file = await open(
98
+ ignore,
99
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0),
100
+ 0o600,
101
+ );
102
+ try {
103
+ await file.writeFile(ACTIVITY_GITIGNORE_CONTENT, "utf8");
104
+ } finally {
105
+ await file.close();
106
+ }
107
+ } catch (error) {
108
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
109
+ // Another cooperating initializer won. Preserve its file and validate its policy below.
110
+ }
111
+ }
112
+ const installed = await lstat(ignore);
113
+ if (!installed.isFile() || installed.isSymbolicLink())
114
+ throw Error("activity ignore path changed; recording unavailable");
115
+ if (repository) {
116
+ // Require the directory itself to be excluded: one sample digest cannot prove that
117
+ // custom rules cover every digest and temporary filename.
118
+ for (const probe of [path, `${path}.lock`, `${join(state, "content")}/`]) {
119
+ try {
120
+ await git("check-ignore", "-q", "--", probe);
121
+ } catch {
122
+ throw Error(
123
+ "existing Git policy does not exclude default activity storage; existing rules were preserved and recording is unavailable",
124
+ );
125
+ }
126
+ }
127
+ }
128
+ }
@@ -4,6 +4,7 @@ import { constants } from "node:fs";
4
4
  import { appendFile, mkdir, open, readFile, realpath, rename, writeFile } from "node:fs/promises";
5
5
  import { dirname, join, resolve, sep } from "node:path";
6
6
  import { activityTimelinePath } from "../kernel/project-paths.ts";
7
+ import { prepareDefaultActivityStorage } from "./activity-storage.ts";
7
8
  import { isEpisodeId, newEpisodeId } from "../kernel/episode-id.ts";
8
9
  import { ENV_EPISODE_ID } from "../kernel/env-names.ts";
9
10
  import { appendRecord, readRecords } from "../governance/record.ts";
@@ -572,7 +573,10 @@ export class ActivityTimelineRecorder {
572
573
  readonly rootId: string;
573
574
  readonly episodeId: string;
574
575
  private taskId?: string;
576
+ private storageReady?: Promise<void>;
577
+ private readonly cwd: string;
575
578
  constructor(cwd: string, env: NodeJS.ProcessEnv = process.env) {
579
+ this.cwd = cwd;
576
580
  const configured = env[ENV_ACTIVITY_TIMELINE]?.trim();
577
581
  this.enabled = configured !== "off" && configured !== "0";
578
582
  this.contentEnabled =
@@ -584,6 +588,11 @@ export class ActivityTimelineRecorder {
584
588
  this.episodeId = isEpisodeId(inheritedEpisodeId) ? inheritedEpisodeId : newEpisodeId();
585
589
  this.taskId = identity.taskId;
586
590
  }
591
+ /** Await during session_start. Direct recorder users also pass this before any write. */
592
+ prepareStorage(): Promise<void> {
593
+ if (!this.enabled) return Promise.resolve();
594
+ return (this.storageReady ??= prepareDefaultActivityStorage(this.cwd, this.path));
595
+ }
587
596
  get task(): string | undefined {
588
597
  return this.taskId;
589
598
  }
@@ -660,6 +669,7 @@ export class ActivityTimelineRecorder {
660
669
  fields: Omit<Partial<ActivityEvent>, "version" | "id" | "kind" | "at" | "rootId" | "taskId">,
661
670
  ): Promise<void> {
662
671
  if (!this.enabled || !this.taskId) return;
672
+ await this.prepareStorage();
663
673
  const event: ActivityEvent = {
664
674
  version: 1,
665
675
  id: randomUUID(),
@@ -676,6 +686,7 @@ export class ActivityTimelineRecorder {
676
686
  await appendRecord(this.path, "activity", event); // ADR-0076 PR 3d: envelope, lock, damage refusal
677
687
  }
678
688
  private async content(value: string): Promise<ContentReference> {
689
+ await this.prepareStorage();
679
690
  const digest = sha(value),
680
691
  bytes = Buffer.byteLength(value);
681
692
  if (!this.contentEnabled || bytes > MAX_CONTENT_BYTES) return { digest, bytes };