@principles/workbuddy-adapter 0.6.6 → 0.7.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/dist/index.d.ts CHANGED
@@ -14,4 +14,4 @@ export { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS, } from './t
14
14
  export { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence, workbuddyCapabilityDeclarations, WORKBUDDY_EVIDENCE_ADAPTER_VERSION, } from './workbuddy-evidence-recorder.js';
15
15
  export { processWorkbuddyHookInvocation, annotateContextWarnings, type WorkBuddyPdHookResult, } from './pd-hook.js';
16
16
  export { runWorkbuddyWorkspaceWorkerCycle, type WorkbuddyWorkerCycleResult, type WorkbuddyWorkerCycleOptions, type WorkbuddyWorkerCycleStepReport, type WorkbuddyWorkerMode, } from './worker/workspace-worker.js';
17
- export { encodeWorkbuddyCwd, deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, decodeWorkbuddyTranscriptWindow, createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, type WorkbuddyTranscriptFileIdentity, type WorkbuddyTranscriptPathValidation, type DecodedWorkbuddyDelta, type DecodeWorkbuddyWindowInput, type WorkbuddyTranscriptSourceContext, ingestWorkbuddyConversation, workbuddyIngestionHints, catchUpWorkbuddyIngestion, locateWorkbuddyTranscriptBySessionIdentity, type WorkbuddyIngestionOptions, type WorkbuddyIngestionOutcome, type WorkbuddyCatchUpOptions, type WorkbuddyCatchUpResult, } from './ingestion/index.js';
17
+ export { encodeWorkbuddyCwd, deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, resolveWorkbuddyProjectsRoot, decodeWorkbuddyTranscriptWindow, createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, type WorkbuddyTranscriptFileIdentity, type WorkbuddyTranscriptPathValidation, type DecodedWorkbuddyDelta, type DecodeWorkbuddyWindowInput, type WorkbuddyTranscriptSourceContext, ingestWorkbuddyConversation, workbuddyIngestionHints, catchUpWorkbuddyIngestion, locateWorkbuddyTranscriptBySessionIdentity, type WorkbuddyIngestionOptions, type WorkbuddyIngestionOutcome, type WorkbuddyCatchUpOptions, type WorkbuddyCatchUpResult, } from './ingestion/index.js';
package/dist/index.js CHANGED
@@ -14,4 +14,4 @@ export { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS, } from './t
14
14
  export { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence, workbuddyCapabilityDeclarations, WORKBUDDY_EVIDENCE_ADAPTER_VERSION, } from './workbuddy-evidence-recorder.js';
15
15
  export { processWorkbuddyHookInvocation, annotateContextWarnings, } from './pd-hook.js';
16
16
  export { runWorkbuddyWorkspaceWorkerCycle, } from './worker/workspace-worker.js';
17
- export { encodeWorkbuddyCwd, deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, decodeWorkbuddyTranscriptWindow, createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, ingestWorkbuddyConversation, workbuddyIngestionHints, catchUpWorkbuddyIngestion, locateWorkbuddyTranscriptBySessionIdentity, } from './ingestion/index.js';
17
+ export { encodeWorkbuddyCwd, deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, resolveWorkbuddyProjectsRoot, decodeWorkbuddyTranscriptWindow, createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, ingestWorkbuddyConversation, workbuddyIngestionHints, catchUpWorkbuddyIngestion, locateWorkbuddyTranscriptBySessionIdentity, } from './ingestion/index.js';
@@ -22,11 +22,10 @@
22
22
  * change, no second source of truth — checkpoints stay the authority.
23
23
  */
24
24
  import fs from 'node:fs';
25
- import os from 'node:os';
26
25
  import path from 'node:path';
27
26
  import { deferGovernanceCheckpoint, listGovernanceCheckpoints, readConversationIngestionConsent } from '@principles/host-runtime';
28
27
  import { ingestWorkbuddyConversation } from './ingestion.js';
29
- import { validateWorkbuddyTranscriptPath, workbuddyProjectsRoot } from './transcript-path.js';
28
+ import { resolveWorkbuddyProjectsRoot, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot } from './transcript-path.js';
30
29
  const DEFAULT_MAX_ROLLOUTS = 8;
31
30
  /** Mirrors the locator's main-session file-name contract; refuse odd identities. */
32
31
  const SESSION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -109,7 +108,20 @@ export function catchUpWorkbuddyIngestion(options) {
109
108
  examined: 0, ingested: 0, warnings: [],
110
109
  };
111
110
  }
112
- const projectsRoot = workbuddyProjectsRoot(options.home ?? os.homedir());
111
+ // An explicit home (worker env / test injection) keeps the historical
112
+ // `<home>/.workbuddy/projects` derivation; the default follows the shared
113
+ // PD Home authority so an experiment never reads the production WorkBuddy
114
+ // transcript tree (rc-9: structured degradation, never a silent fallback).
115
+ const projectsRootResolution = options.home !== undefined
116
+ ? { ok: true, root: workbuddyProjectsRoot(options.home) }
117
+ : resolveWorkbuddyProjectsRoot();
118
+ if (!projectsRootResolution.ok) {
119
+ return {
120
+ status: 'degraded', reason: projectsRootResolution.reason, nextAction: projectsRootResolution.nextAction,
121
+ examined: 0, ingested: 0, warnings: [],
122
+ };
123
+ }
124
+ const projectsRoot = projectsRootResolution.root;
113
125
  const limit = Math.max(1, Math.min(options.maxRollouts ?? DEFAULT_MAX_ROLLOUTS, 32));
114
126
  const checkpoints = listed.checkpoints.slice(0, limit);
115
127
  let ingested = 0;
@@ -6,7 +6,7 @@
6
6
  * TranscriptSourceAdapter the shared host-runtime pipeline drives.
7
7
  */
8
8
  export { encodeWorkbuddyCwd } from './encode-cwd.js';
9
- export { deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, type WorkbuddyTranscriptFileIdentity, type WorkbuddyTranscriptPathValidation, } from './transcript-path.js';
9
+ export { deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, resolveWorkbuddyProjectsRoot, type WorkbuddyTranscriptFileIdentity, type WorkbuddyTranscriptPathValidation, } from './transcript-path.js';
10
10
  export { decodeWorkbuddyTranscriptWindow, type DecodedWorkbuddyDelta, type DecodeWorkbuddyWindowInput, } from './transcript-decoder.js';
11
11
  export { createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, type WorkbuddyTranscriptSourceContext, } from './transcript-source.js';
12
12
  export { ingestWorkbuddyConversation, workbuddyIngestionHints, type WorkbuddyIngestionOptions, type WorkbuddyIngestionOutcome, } from './ingestion.js';
@@ -6,7 +6,7 @@
6
6
  * TranscriptSourceAdapter the shared host-runtime pipeline drives.
7
7
  */
8
8
  export { encodeWorkbuddyCwd } from './encode-cwd.js';
9
- export { deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, } from './transcript-path.js';
9
+ export { deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, resolveWorkbuddyProjectsRoot, } from './transcript-path.js';
10
10
  export { decodeWorkbuddyTranscriptWindow, } from './transcript-decoder.js';
11
11
  export { createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, } from './transcript-source.js';
12
12
  export { ingestWorkbuddyConversation, workbuddyIngestionHints, } from './ingestion.js';
@@ -1,3 +1,21 @@
1
+ /**
2
+ * WorkBuddy conversation-ingestion orchestrator (PRI-1171 P2, ticket ⑤).
3
+ *
4
+ * Connects the EXISTING pieces — the unified host-runtime pipeline, the
5
+ * WorkBuddy TranscriptSourceAdapter from ticket ④, the v3 consent ledger and
6
+ * the workspace feature flags — without introducing a new subsystem. The hook
7
+ * calls `ingestWorkbuddyConversation` on `turn_complete`; the worker calls the
8
+ * catch-up sibling. Both go through this same gate ordering.
9
+ *
10
+ * Gate order is a hard privacy invariant (SPEC §8.2 / §10):
11
+ * 1. resolved flags (host.workbuddy AND workbuddy_conversation_ingestion);
12
+ * 2. the REAL v3 consent record for hostKind='workbuddy';
13
+ * 3. only then any transcript filesystem read (pipeline's port).
14
+ * Steps 1 and 2 perform ZERO transcript port calls. Unlike the Codex path
15
+ * (which still hard-codes `consent: 'granted'` from its setup-flow invariant),
16
+ * this host reads the ledger at runtime, so revoking consent takes effect
17
+ * immediately.
18
+ */
1
19
  import { type HookHints, type TranscriptPort } from '@principles/host-runtime';
2
20
  export interface WorkbuddyIngestionOptions {
3
21
  /** Governance workspace (OD-07) — the v3 ledger and trajectory.db live here. */
@@ -16,8 +16,8 @@
16
16
  * this host reads the ledger at runtime, so revoking consent takes effect
17
17
  * immediately.
18
18
  */
19
- import os from 'node:os';
20
19
  import { readConversationIngestionConsent, runConversationIngestion, } from '@principles/host-runtime';
20
+ import { resolveWorkbuddyProjectsRoot, workbuddyProjectsRoot } from './transcript-path.js';
21
21
  import { createWorkbuddyTranscriptSource } from './transcript-source.js';
22
22
  /** Runtime-contract guard (rc-1): a non-null, non-array object is the only trusted payload shape. */
23
23
  function isRecord(value) {
@@ -86,6 +86,24 @@ export function ingestWorkbuddyConversation(options) {
86
86
  nextAction: 'Record a granted WorkBuddy ingestion decision with `pd workbuddy setup --accept` before any transcript is read.',
87
87
  };
88
88
  }
89
+ // 2b. Host transcript-root authority gate — BEFORE any transcript port
90
+ // call. The default follows the shared PD Home authority
91
+ // (WORKBUDDY_CONFIG_DIR override, PD_EXPERIMENT_ROOT isolation) so an
92
+ // experiment never reads the production WorkBuddy transcript tree; a
93
+ // refused resolution degrades observably instead of silently falling back
94
+ // to the OS home. An explicit options.home keeps the raw-home contract of
95
+ // the seam port (locate derives `<home>/.workbuddy/projects`).
96
+ const projectsRootResolution = options.home !== undefined
97
+ ? { ok: true, root: workbuddyProjectsRoot(options.home) }
98
+ : resolveWorkbuddyProjectsRoot();
99
+ if (!projectsRootResolution.ok) {
100
+ return {
101
+ status: 'degraded',
102
+ reason: projectsRootResolution.reason,
103
+ nextAction: projectsRootResolution.nextAction,
104
+ warnings: [],
105
+ };
106
+ }
89
107
  // 3. Never ingest from a recursively-triggered Stop hook.
90
108
  if (isRecord(options.rawPayload) && own(options.rawPayload, 'stop_hook_active') === true) {
91
109
  return {
@@ -105,7 +123,7 @@ export function ingestWorkbuddyConversation(options) {
105
123
  source: createWorkbuddyTranscriptSource({ now }),
106
124
  session,
107
125
  hints: workbuddyIngestionHints(options.rawPayload),
108
- env: { home: options.home ?? os.homedir() },
126
+ env: options.home !== undefined ? { home: options.home } : {},
109
127
  // The pipeline re-checks both gates; passing the real decision keeps a
110
128
  // single source of truth and makes the port-spy invariant observable.
111
129
  flags: { ingestionEnabled: true },
@@ -1,3 +1,4 @@
1
+ import { type PdHomePaths } from '@principles/install-layout';
1
2
  /** File identity captured at validation; the seam port re-proves it post-open. */
2
3
  export interface WorkbuddyTranscriptFileIdentity {
3
4
  readonly dev: number;
@@ -17,6 +18,14 @@ export type WorkbuddyTranscriptPathValidation = {
17
18
  };
18
19
  /** Projects root: `<home>/.workbuddy/projects` (engine-side join, forensics §2.2). */
19
20
  export declare function workbuddyProjectsRoot(home: string): string;
21
+ export declare function resolveWorkbuddyProjectsRoot(homePaths?: PdHomePaths): {
22
+ ok: true;
23
+ root: string;
24
+ } | {
25
+ ok: false;
26
+ reason: string;
27
+ nextAction: string;
28
+ };
20
29
  /**
21
30
  * Authorize one transcript path against the WorkBuddy projects root.
22
31
  *
@@ -28,12 +37,12 @@ export declare function workbuddyProjectsRoot(home: string): string;
28
37
  export declare function validateWorkbuddyTranscriptPath(transcriptPath: string, projectsRoot: string): WorkbuddyTranscriptPathValidation;
29
38
  /**
30
39
  * Deterministic derivation (fallback when no hook payload path exists):
31
- * `<home>/.workbuddy/projects/<encodeCwd(cwd)>/<sessionId>.jsonl`. Returns
32
- * null when the session identity or cwd cannot produce a contract-shaped
33
- * path — the caller degrades, it never scans for a "latest" file.
40
+ * `<projectsRoot>/<encodeCwd(cwd)>/<sessionId>.jsonl`. Returns null when the
41
+ * session identity or cwd cannot produce a contract-shaped path — the caller
42
+ * degrades, it never scans for a "latest" file.
34
43
  */
35
44
  export declare function deriveWorkbuddyTranscriptPath(input: {
36
- home: string;
45
+ projectsRoot: string;
37
46
  cwd: string;
38
47
  sessionId: string;
39
48
  }): string | null;
@@ -21,7 +21,69 @@
21
21
  */
22
22
  import fs from 'node:fs';
23
23
  import path from 'node:path';
24
+ import { isPathWithinRoot, resolvePdHome } from '@principles/install-layout';
24
25
  import { encodeWorkbuddyCwd } from './encode-cwd.js';
26
+ /**
27
+ * Experiment boundary verification for the WorkBuddy projects root.
28
+ *
29
+ * The projects LEAF is not a PdHomePaths field, so resolvePdHome's boundary
30
+ * pass does not see `<workbuddyConfigDir>/projects` — a junction there pointing
31
+ * at the production transcript store would resolvePdHome cleanly and then read
32
+ * production conversations. Resolution walks to the deepest EXISTING ancestor
33
+ * (the dir is created lazily), re-appends the missing tail, and refuses when:
34
+ * - any re-appended segment EXISTS but cannot be resolved (broken /
35
+ * self-looping link → "cannot safely verify" must not pass as
36
+ * "does not exist yet");
37
+ * - or the composed canonical path sits outside the experiment root
38
+ * (an existing link into production is an escape, not a child).
39
+ * Production mode (no PD_EXPERIMENT_ROOT) has no boundary and is unchanged.
40
+ */
41
+ function verifyProjectsRootBoundary(root, experimentRoot) {
42
+ const missing = [];
43
+ let current = path.resolve(root);
44
+ for (;;) {
45
+ let real;
46
+ try {
47
+ real = fs.realpathSync.native(current);
48
+ }
49
+ catch {
50
+ const parent = path.dirname(current);
51
+ if (parent === current) {
52
+ return {
53
+ ok: false,
54
+ reason: 'workbuddy_projects_root_unresolvable',
55
+ nextAction: `Cannot canonically resolve any ancestor of ${root}; refusing to derive a transcript root that cannot be verified.`,
56
+ };
57
+ }
58
+ missing.push(path.basename(current));
59
+ current = parent;
60
+ continue;
61
+ }
62
+ let tail = real;
63
+ for (const segment of missing.reverse()) {
64
+ tail = path.join(tail, segment);
65
+ try {
66
+ fs.lstatSync(tail);
67
+ }
68
+ catch {
69
+ continue; // genuinely absent — the lazy-creation contract
70
+ }
71
+ return {
72
+ ok: false,
73
+ reason: 'workbuddy_projects_root_unverifiable',
74
+ nextAction: `${tail} exists but cannot be resolved (broken/self-looping link). Remove it or point it inside the experiment root ${experimentRoot}.`,
75
+ };
76
+ }
77
+ if (!isPathWithinRoot(experimentRoot, tail)) {
78
+ return {
79
+ ok: false,
80
+ reason: 'workbuddy_projects_root_escapes_experiment',
81
+ nextAction: `Remove the symlink/junction at ${root} (or point it inside the experiment root ${experimentRoot}) and retry.`,
82
+ };
83
+ }
84
+ return { ok: true };
85
+ }
86
+ }
25
87
  const SESSION_FILE_NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.jsonl$/;
26
88
  /** Canonicalize to the final long form (native realpath first; 8.3-safe, mirrors the Codex locator). */
27
89
  function canonicalizePath(target) {
@@ -39,6 +101,42 @@ function hasParentTraversal(value) {
39
101
  export function workbuddyProjectsRoot(home) {
40
102
  return path.join(home, '.workbuddy', 'projects');
41
103
  }
104
+ /**
105
+ * Default WorkBuddy transcript projects root for discovery. Follows the shared
106
+ * PD Home authority (WORKBUDDY_CONFIG_DIR override, PD_EXPERIMENT_ROOT
107
+ * isolation) so an experiment reads its own lab transcripts — never the
108
+ * production host's. A refused resolution is a structured degradation for
109
+ * read-only callers (rc-9), never a silent fallback to the OS home.
110
+ *
111
+ * An already-resolved `PdHomePaths` (the caller's single-parse authority, e.g.
112
+ * `pd health`) may be injected; the SAME experiment boundary verification
113
+ * applies — the projects leaf is still not a PdHomePaths field.
114
+ */
115
+ /**
116
+ * Boundary-checked projects-root derivation from ONE already-resolved PD Home.
117
+ * The projects LEAF is not a PdHomePaths field — verify it in experiment mode.
118
+ */
119
+ function resolveProjectsRootFromPdHome(pdHome) {
120
+ const root = path.join(pdHome.workbuddyConfigDir, 'projects');
121
+ if (pdHome.experimentRoot !== undefined) {
122
+ const boundary = verifyProjectsRootBoundary(root, pdHome.experimentRoot);
123
+ if (!boundary.ok)
124
+ return boundary;
125
+ }
126
+ return { ok: true, root };
127
+ }
128
+ export function resolveWorkbuddyProjectsRoot(homePaths) {
129
+ // An already-resolved PdHomePaths (the caller's single-parse authority, e.g.
130
+ // `pd health`) skips the re-resolution but gets the SAME boundary check.
131
+ if (homePaths !== undefined) {
132
+ return resolveProjectsRootFromPdHome(homePaths);
133
+ }
134
+ const pdHome = resolvePdHome();
135
+ if (!pdHome.ok) {
136
+ return { ok: false, reason: `pd_home_resolution_failed:${pdHome.reason}`, nextAction: pdHome.nextAction };
137
+ }
138
+ return resolveProjectsRootFromPdHome(pdHome);
139
+ }
42
140
  /**
43
141
  * Authorize one transcript path against the WorkBuddy projects root.
44
142
  *
@@ -101,9 +199,9 @@ function encodeCwdSafe(cwd) {
101
199
  }
102
200
  /**
103
201
  * Deterministic derivation (fallback when no hook payload path exists):
104
- * `<home>/.workbuddy/projects/<encodeCwd(cwd)>/<sessionId>.jsonl`. Returns
105
- * null when the session identity or cwd cannot produce a contract-shaped
106
- * path — the caller degrades, it never scans for a "latest" file.
202
+ * `<projectsRoot>/<encodeCwd(cwd)>/<sessionId>.jsonl`. Returns null when the
203
+ * session identity or cwd cannot produce a contract-shaped path — the caller
204
+ * degrades, it never scans for a "latest" file.
107
205
  */
108
206
  export function deriveWorkbuddyTranscriptPath(input) {
109
207
  if (input.sessionId.length === 0 || input.cwd.length === 0)
@@ -113,5 +211,5 @@ export function deriveWorkbuddyTranscriptPath(input) {
113
211
  const encoded = encodeCwdSafe(input.cwd);
114
212
  if (encoded === null)
115
213
  return null;
116
- return path.join(workbuddyProjectsRoot(input.home), encoded, `${input.sessionId.toLowerCase()}.jsonl`);
214
+ return path.join(input.projectsRoot, encoded, `${input.sessionId.toLowerCase()}.jsonl`);
117
215
  }
@@ -22,8 +22,7 @@
22
22
  * catch-up keeps ingesting, the health surface shows the lag.
23
23
  */
24
24
  import fs from 'node:fs';
25
- import os from 'node:os';
26
- import { deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot } from './transcript-path.js';
25
+ import { deriveWorkbuddyTranscriptPath, resolveWorkbuddyProjectsRoot, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot } from './transcript-path.js';
27
26
  import { decodeWorkbuddyTranscriptWindow } from './transcript-decoder.js';
28
27
  /** Single-session alert threshold (tech design §12). */
29
28
  export const WORKBUDDY_SINGLE_SESSION_ALERT_BYTES = 50 * 1024 * 1024;
@@ -40,6 +39,70 @@ function existsFile(target) {
40
39
  return false;
41
40
  }
42
41
  }
42
+ /**
43
+ * Resolve the session transcript against one concrete projects root, in
44
+ * priority order: a non-empty hook hint (validated AND identity-bound to this
45
+ * hook's session), then the deterministic
46
+ * `<projectsRoot>/<encodeCwd(cwd)>/<sessionId>.jsonl` path. Never scans
47
+ * directories; every refusal carries a reason + nextAction.
48
+ */
49
+ function locateTranscript(session, hints, projectsRoot) {
50
+ // 1. Hook-payload paths, empty strings skipped (forensics §6.2).
51
+ const hinted = nonEmptyHint(hints.transcriptPath) ?? nonEmptyHint(hints.agentTranscriptPath);
52
+ if (hinted !== null) {
53
+ const validated = validateWorkbuddyTranscriptPath(hinted, projectsRoot);
54
+ if (!validated.ok)
55
+ return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction };
56
+ // Session binding (P2 review): a contract-shaped path inside the
57
+ // projects root can still belong to ANOTHER session. Reading it would
58
+ // file that session's evidence under this hook's rollout identity, so
59
+ // the path's identity must equal the host session identity. The check
60
+ // compares the PARSED identity, never just the file name shape.
61
+ const hookSessionId = session.sessionId.trim().toLowerCase();
62
+ if (hookSessionId.length === 0) {
63
+ return {
64
+ status: 'degraded',
65
+ reason: 'transcript_session_unverified',
66
+ nextAction: 'the hook payload has no session_id, so the transcript path cannot be bound to this session; nothing is read.',
67
+ };
68
+ }
69
+ if (validated.sessionIdentity !== hookSessionId) {
70
+ return {
71
+ status: 'degraded',
72
+ reason: 'transcript_session_mismatch',
73
+ nextAction: `the hinted transcript belongs to session ${validated.sessionIdentity}, not ${hookSessionId}; PD refuses to read another session's evidence.`,
74
+ };
75
+ }
76
+ return { status: 'ok', filePath: validated.canonicalPath, expectedIdentity: validated.identity, sessionIdentity: validated.sessionIdentity };
77
+ }
78
+ // 2. Deterministic derivation from the session identity + cwd.
79
+ const derived = deriveWorkbuddyTranscriptPath({ projectsRoot, cwd: session.cwd ?? '', sessionId: session.sessionId });
80
+ if (derived === null) {
81
+ return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'no hook transcript path and no derivable session transcript; nothing is read or fabricated.' };
82
+ }
83
+ const validated = validateWorkbuddyTranscriptPath(derived, projectsRoot);
84
+ if (!validated.ok && validated.reason === 'transcript_path_invalid' && !existsFile(derived)) {
85
+ // The derived session file simply does not exist yet — neutral
86
+ // unavailability, not an invalid payload.
87
+ return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'no WorkBuddy transcript exists yet for this session; nothing is read or fabricated.' };
88
+ }
89
+ if (!validated.ok)
90
+ return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction };
91
+ // Same session binding as the hinted branch (P2 review): the derived
92
+ // file name is shaped from the session id, but a symlinked
93
+ // <sessionId>.jsonl can resolve to ANOTHER session's transcript. Only the
94
+ // canonical identity is authoritative; never file another session's
95
+ // evidence under this session.
96
+ const derivedSessionId = session.sessionId.trim().toLowerCase();
97
+ if (derivedSessionId.length === 0 || validated.sessionIdentity !== derivedSessionId) {
98
+ return {
99
+ status: 'degraded',
100
+ reason: 'transcript_session_mismatch',
101
+ nextAction: `the derived transcript resolves to session ${validated.sessionIdentity}, not ${derivedSessionId}; PD refuses to read another session's evidence.`,
102
+ };
103
+ }
104
+ return { status: 'ok', filePath: validated.canonicalPath, expectedIdentity: validated.identity, sessionIdentity: validated.sessionIdentity };
105
+ }
43
106
  /**
44
107
  * Build the WorkBuddy {@link TranscriptSourceAdapter} for the host-neutral
45
108
  * conversation-ingestion seam. Locating is deterministic (hint first, then the
@@ -55,63 +118,18 @@ export function createWorkbuddyTranscriptSource(context) {
55
118
  * Never scans directories; every refusal carries a reason + nextAction.
56
119
  */
57
120
  locate(session, hints, env) {
58
- const home = env.home ?? context.home ?? os.homedir();
59
- const projectsRoot = workbuddyProjectsRoot(home);
60
- // 1. Hook-payload paths, empty strings skipped (forensics §6.2).
61
- const hinted = nonEmptyHint(hints.transcriptPath) ?? nonEmptyHint(hints.agentTranscriptPath);
62
- if (hinted !== null) {
63
- const validated = validateWorkbuddyTranscriptPath(hinted, projectsRoot);
64
- if (!validated.ok)
65
- return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction };
66
- // Session binding (P2 review): a contract-shaped path inside the
67
- // projects root can still belong to ANOTHER session. Reading it would
68
- // file that session's evidence under this hook's rollout identity, so
69
- // the path's identity must equal the host session identity. The check
70
- // compares the PARSED identity, never just the file name shape.
71
- const hookSessionId = session.sessionId.trim().toLowerCase();
72
- if (hookSessionId.length === 0) {
73
- return {
74
- status: 'degraded',
75
- reason: 'transcript_session_unverified',
76
- nextAction: 'the hook payload has no session_id, so the transcript path cannot be bound to this session; nothing is read.',
77
- };
78
- }
79
- if (validated.sessionIdentity !== hookSessionId) {
80
- return {
81
- status: 'degraded',
82
- reason: 'transcript_session_mismatch',
83
- nextAction: `the hinted transcript belongs to session ${validated.sessionIdentity}, not ${hookSessionId}; PD refuses to read another session's evidence.`,
84
- };
85
- }
86
- return { status: 'ok', filePath: validated.canonicalPath, expectedIdentity: validated.identity, sessionIdentity: validated.sessionIdentity };
87
- }
88
- // 2. Deterministic derivation from the session identity + cwd.
89
- const derived = deriveWorkbuddyTranscriptPath({ home, cwd: session.cwd ?? '', sessionId: session.sessionId });
90
- if (derived === null) {
91
- return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'no hook transcript path and no derivable session transcript; nothing is read or fabricated.' };
92
- }
93
- const validated = validateWorkbuddyTranscriptPath(derived, projectsRoot);
94
- if (!validated.ok && validated.reason === 'transcript_path_invalid' && !existsFile(derived)) {
95
- // The derived session file simply does not exist yet — neutral
96
- // unavailability, not an invalid payload.
97
- return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'no WorkBuddy transcript exists yet for this session; nothing is read or fabricated.' };
98
- }
99
- if (!validated.ok)
100
- return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction };
101
- // Same session binding as the hinted branch (P2 review): the derived
102
- // file name is shaped from the session id, but a symlinked
103
- // <sessionId>.jsonl can resolve to ANOTHER session's transcript. Only the
104
- // canonical identity is authoritative; never file another session's
105
- // evidence under this session.
106
- const derivedSessionId = session.sessionId.trim().toLowerCase();
107
- if (derivedSessionId.length === 0 || validated.sessionIdentity !== derivedSessionId) {
108
- return {
109
- status: 'degraded',
110
- reason: 'transcript_session_mismatch',
111
- nextAction: `the derived transcript resolves to session ${validated.sessionIdentity}, not ${derivedSessionId}; PD refuses to read another session's evidence.`,
112
- };
121
+ // An explicit home (hook env / test injection) keeps the historical
122
+ // `<home>/.workbuddy/projects` derivation; the default follows the
123
+ // shared PD Home authority so an experiment never reads the production
124
+ // WorkBuddy transcript tree.
125
+ const home = env.home ?? context.home;
126
+ if (home !== undefined) {
127
+ return locateTranscript(session, hints, workbuddyProjectsRoot(home));
113
128
  }
114
- return { status: 'ok', filePath: validated.canonicalPath, expectedIdentity: validated.identity, sessionIdentity: validated.sessionIdentity };
129
+ const projectsRoot = resolveWorkbuddyProjectsRoot();
130
+ if (!projectsRoot.ok)
131
+ return { status: 'degraded', reason: projectsRoot.reason, nextAction: projectsRoot.nextAction };
132
+ return locateTranscript(session, hints, projectsRoot.root);
115
133
  },
116
134
  /**
117
135
  * Project one byte window into observations. No host contract guard
package/dist/pd-hook.js CHANGED
@@ -32,7 +32,6 @@
32
32
  * neutral means EMPTY stdout, never `{}`. Diagnostics go to stderr only.
33
33
  */
34
34
  import { readFileSync, realpathSync } from 'node:fs';
35
- import os from 'node:os';
36
35
  import path from 'node:path';
37
36
  import process from 'node:process';
38
37
  import { pathToFileURL, fileURLToPath } from 'node:url';
@@ -86,6 +85,10 @@ function workbuddyEventEmitter(stateDir, evidence, readAdaptiveFact) {
86
85
  : {
87
86
  resultCode: `${fact.status}:${fact.reason}`.slice(0, 240),
88
87
  scored: fact.sends > 0,
88
+ // Principle Context S-state (bounded enum): the Console/Owner can
89
+ // tell whether the context actually participated — `sent` only
90
+ // when the request really carried it (SPEC v1.1 sect 5.4.1).
91
+ ...(fact.principleContext !== undefined ? { principleContext: fact.principleContext } : {}),
89
92
  ...(fact.targetActivationId !== null && data.activationIds.includes(fact.targetActivationId)
90
93
  ? { appendedActivationId: fact.targetActivationId }
91
94
  : {}),
@@ -238,7 +241,7 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
238
241
  if (channelEventName === 'UserPromptSubmit' && typeof parsed === 'object' && parsed !== null
239
242
  && Object.getOwnPropertyDescriptor(parsed, 'hook_event_name')?.value === 'UserPromptSubmit'
240
243
  && parseOwnerStatementPrefix(Object.getOwnPropertyDescriptor(parsed, 'prompt')?.value).matched) {
241
- const workspace = resolveWorkbuddyWorkspace(os.homedir());
244
+ const workspace = resolveWorkbuddyWorkspace();
242
245
  if (workspace.status === 'ok') {
243
246
  const config = loadPdConfigForPlugin(workspace.workspaceDir);
244
247
  if (config.ok && computeFeatureFlagsFromConfig(config.effective).flags['host.workbuddy']?.enabled === true) {
@@ -257,7 +260,10 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
257
260
  const hookEpoch = new Date();
258
261
  // OD-07/P06 governance workspace: explicit, user-level, shared across
259
262
  // projects; never auto-created here and never falling back to another host.
260
- const resolution = resolveWorkbuddyWorkspace(os.homedir());
263
+ // No os.homedir() injection: the default HOME-first precedence keeps the
264
+ // hook on the SAME host config root the installer used (Devin review
265
+ // #2699-0006 — an explicit OS-home input splits the root when HOME differs).
266
+ const resolution = resolveWorkbuddyWorkspace();
261
267
  if (resolution.status === 'uninitialized') {
262
268
  return neutralWithDiagnostics([diagnostic('skipped', resolution.reason, resolution.nextAction)]);
263
269
  }
@@ -467,6 +473,7 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
467
473
  reason: line.reason,
468
474
  sends: line.sends,
469
475
  targetActivationId: line.targetActivationId,
476
+ ...(line.principleContext !== undefined ? { principleContext: line.principleContext } : {}),
470
477
  };
471
478
  if (line.status !== 'selected')
472
479
  evidenceDiagnostics.push(diagnostic(line.status === 'unavailable' ? 'degraded' : 'skipped', `adaptive_selection_${line.status}:${line.reason}`, 'Check Adaptive configuration or use Native assembly.'));
@@ -32,7 +32,7 @@
32
32
  import fs from 'node:fs';
33
33
  import path from 'node:path';
34
34
  import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
35
- import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
35
+ import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createHostIntentDocReader, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
36
36
  import { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS } from '../tool-semantics.js';
37
37
  import { catchUpWorkbuddyIngestion } from '../ingestion/catch-up.js';
38
38
  const WORKER_OWNER = 'companion-worker';
@@ -165,6 +165,13 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
165
165
  owner: WORKER_OWNER,
166
166
  effectiveConfig: config.effective,
167
167
  getEnvVar: (name) => process.env[name],
168
+ // PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
169
+ // for governance-admitted WorkBuddy pains — the neutral host reader
170
+ // must ride along (flag-off = zero filesystem access inside it).
171
+ intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
172
+ // PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
173
+ // turns from the workspace's own consent-tiered governance store.
174
+ trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir }),
168
175
  });
169
176
  const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
170
177
  diagnostician = {
@@ -9,7 +9,14 @@ export type WorkbuddyWorkspaceResolution = {
9
9
  } | {
10
10
  status: 'degraded';
11
11
  workspaceDir: string;
12
- reason: 'workbuddy_workspace_config_invalid' | 'workbuddy_workspace_config_unreadable';
12
+ reason: 'pd_home_resolution_failed' | 'workbuddy_workspace_config_invalid' | 'workbuddy_workspace_config_unreadable';
13
13
  nextAction: string;
14
14
  };
15
- export declare function resolveWorkbuddyWorkspace(homeDir: string): WorkbuddyWorkspaceResolution;
15
+ /**
16
+ * Resolve the WorkBuddy governance workspace through the shared PD Home
17
+ * authority. `homeDir` stays OPTIONAL and is a TEST injection only: the
18
+ * default resolution uses the shared HOME-first precedence, so hooks and the
19
+ * installer land on the same host config root even when HOME ≠ os.homedir()
20
+ * (Devin review #2699-0006).
21
+ */
22
+ export declare function resolveWorkbuddyWorkspace(homeDir?: string, env?: Readonly<Record<string, string | undefined>>): WorkbuddyWorkspaceResolution;
@@ -17,9 +17,25 @@
17
17
  */
18
18
  import { statSync } from 'node:fs';
19
19
  import path from 'node:path';
20
- import { getWorkbuddyWorkspaceDir } from '@principles/install-layout';
21
- export function resolveWorkbuddyWorkspace(homeDir) {
22
- const workspaceDir = getWorkbuddyWorkspaceDir(homeDir);
20
+ import { resolvePdHome } from '@principles/install-layout';
21
+ /**
22
+ * Resolve the WorkBuddy governance workspace through the shared PD Home
23
+ * authority. `homeDir` stays OPTIONAL and is a TEST injection only: the
24
+ * default resolution uses the shared HOME-first precedence, so hooks and the
25
+ * installer land on the same host config root even when HOME ≠ os.homedir()
26
+ * (Devin review #2699-0006).
27
+ */
28
+ export function resolveWorkbuddyWorkspace(homeDir, env = process.env) {
29
+ const pdHome = resolvePdHome({ env, ...(homeDir !== undefined ? { homeDir } : {}) });
30
+ if (!pdHome.ok) {
31
+ return {
32
+ status: 'degraded',
33
+ workspaceDir: '',
34
+ reason: 'pd_home_resolution_failed',
35
+ nextAction: `PD refused to resolve the WorkBuddy workspace: ${pdHome.message} ${pdHome.nextAction}`,
36
+ };
37
+ }
38
+ const workspaceDir = pdHome.workbuddyWorkspaceDir;
23
39
  const configPath = path.join(workspaceDir, '.pd', 'config.yaml');
24
40
  let stat;
25
41
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/workbuddy-adapter",
3
- "version": "0.6.6",
3
+ "version": "0.7.0",
4
4
  "description": "WorkBuddy host adapter for Principles Disciple — implements the HostAdapter interface for WorkBuddy's Git Bash command-hook model (ADR-0020 third host, SPEC workbuddy-host-adapter v0.3.0).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -42,9 +42,9 @@
42
42
  "lint": "eslint \"src/**/*.ts\""
43
43
  },
44
44
  "dependencies": {
45
- "@principles/core": "^7.9.0",
46
- "@principles/host-runtime": "^4.3.0",
47
- "@principles/install-layout": "^0.8.1"
45
+ "@principles/core": "^8.0.0",
46
+ "@principles/host-runtime": "^4.5.0",
47
+ "@principles/install-layout": "^0.9.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@types/node": "^26.6.6",
@@ -61,5 +61,5 @@
61
61
  "publishConfig": {
62
62
  "access": "public"
63
63
  },
64
- "gitHead": "97cac4b30eb64ad4b369d2f86f5c57a8053897eb"
64
+ "gitHead": "95de4c633aedd4d588286c665baf3af816f6250a"
65
65
  }
@@ -84,6 +84,7 @@ const INITIAL_ENV_PRESENCE = Object.freeze({
84
84
  const logState = {
85
85
  host: 'unknown',
86
86
  bindingPathExists: false,
87
+ bindingSource: 'not_checked',
87
88
  workspaceResolution: 'not_checked',
88
89
  seq: 0,
89
90
  runId: null,
@@ -354,13 +355,221 @@ function isInside(parent, child) {
354
355
  return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
355
356
  }
356
357
 
358
+ // PRI-1247: a binding must never point one host at ANOTHER host's owned default
359
+ // governance workspace (the Codex installer used to inherit the OpenClaw
360
+ // detection result). This mirrors `findForeignWorkspaceHost` in
361
+ // @principles/install-layout; the parity test pins both sides together.
362
+ function hostOwnedWorkspaces(bindingHost, roots) {
363
+ switch (bindingHost) {
364
+ case 'openclaw':
365
+ return [path.join(roots.homeDir, 'clawd'), path.join(roots.openclawHome, 'workspace')];
366
+ case 'codex':
367
+ return [path.join(roots.codexHome, 'pd-workspace')];
368
+ case 'workbuddy':
369
+ return [path.join(roots.workbuddyConfigDir, 'pd-workspace')];
370
+ default:
371
+ return [];
372
+ }
373
+ }
374
+
375
+ function findForeignWorkspaceOwner(bindingHost, workspaceDir, roots) {
376
+ if (typeof workspaceDir !== 'string' || workspaceDir.trim().length === 0) return [];
377
+ // Final directory identity: a binding whose path reaches another host's tree
378
+ // through a junction, alias or case difference must not escape the check.
379
+ // Identity NORMALIZATION only — every directory SOURCE stays the #2699 PD
380
+ // Home roots authority (no second layout source).
381
+ const target = canonicalDirIdentity(workspaceDir);
382
+ const owners = [];
383
+ const claim = (other) => { if (!owners.includes(other)) owners.push(other); };
384
+ for (const other of KNOWN_HOSTS) {
385
+ if (other === bindingHost) continue;
386
+ for (const owned of hostOwnedWorkspaces(other, roots)) {
387
+ if (isInsideOrSame(canonicalDirIdentity(owned), target)) claim(other);
388
+ }
389
+ }
390
+ // PRI-1247 reopen: default-dir enumeration alone accepted a NON-DEFAULT
391
+ // workspace another host FORMALLY declared (`~/.openclaw/principles-disciple.json`
392
+ // `workspace`, or the host payload's own mcp-binding.json `workspaceDir`).
393
+ // Those declarations close the hole the original incident used. This mirrors
394
+ // `findForeignWorkspaceOwner` in @principles/install-layout; the parity test
395
+ // pins both sides together.
396
+ for (const declared of hostDeclaredWorkspaceClaims(roots)) {
397
+ if (declared.host === bindingHost) continue;
398
+ if (isInsideOrSame(canonicalDirIdentity(declared.workspaceDir), target)) claim(declared.host);
399
+ }
400
+ return owners;
401
+ }
402
+
403
+ // Final directory identity: the realpath when it resolves (junctions/symlinks
404
+ // and case folded by the OS), else the resolved lexical form — the same rule
405
+ // as `workspaceIdentity` in @principles/install-layout.
406
+ function canonicalDirIdentity(dir) {
407
+ let resolved;
408
+ try {
409
+ resolved = fs.realpathSync.native(dir);
410
+ } catch {
411
+ resolved = path.resolve(dir);
412
+ }
413
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
414
+ }
415
+
416
+ function readAbsoluteWorkspaceField(parsed, field) {
417
+ if (parsed === undefined) return undefined;
418
+ const value = parsed[field];
419
+ if (typeof value !== 'string' || value.trim().length === 0) return undefined;
420
+ if (!path.isAbsolute(value.trim())) return undefined;
421
+ return path.resolve(value.trim());
422
+ }
423
+
424
+ /**
425
+ * The hosts' FORMAL workspace declarations (dependency-free mirror of
426
+ * `collectHostWorkspaceClaims`' declaration part in @principles/install-layout):
427
+ * - OpenClaw: the `workspace` field of `~/.openclaw/principles-disciple.json`
428
+ * (fallback `~/.principles/principles-disciple.json`) — the Owner's explicit
429
+ * PD declaration, which may point at a NON-DEFAULT directory;
430
+ * - Codex: every PLUGIN_DATA payload binding (`plugins/data` child directories
431
+ * named `principles-disciple-<marketplace>`, file `mcp-binding.json`,
432
+ * field `workspaceDir`);
433
+ * - WorkBuddy: the marketplace payload binding
434
+ * (`~/.pd/workbuddy-marketplace/principles-disciple/mcp-binding.json`).
435
+ * Comparison uses canonical directory identity so a junction, alias or case
436
+ * difference cannot smuggle one host's tree past another host's claim.
437
+ */
438
+ function hostDeclaredWorkspaceClaims(roots) {
439
+ const claims = [];
440
+ const declarationFiles = [
441
+ path.join(roots.openclawHome, 'principles-disciple.json'),
442
+ path.join(roots.homeDir, '.principles', 'principles-disciple.json'),
443
+ ];
444
+ for (const file of declarationFiles) {
445
+ const declared = readAbsoluteWorkspaceField(readJson(file), 'workspace');
446
+ if (declared !== undefined) claims.push({ host: 'openclaw', workspaceDir: declared });
447
+ }
448
+ try {
449
+ const dataRoot = path.join(roots.codexHome, 'plugins', 'data');
450
+ for (const entry of fs.readdirSync(dataRoot)) {
451
+ if (typeof entry !== 'string' || !entry.startsWith('principles-disciple-')) continue;
452
+ const bound = readAbsoluteWorkspaceField(readJson(path.join(dataRoot, entry, 'mcp-binding.json')), 'workspaceDir');
453
+ if (bound !== undefined) claims.push({ host: 'codex', workspaceDir: bound });
454
+ }
455
+ } catch {
456
+ // No Codex plugin data on this machine — nothing to claim.
457
+ }
458
+ const wbBound = readAbsoluteWorkspaceField(
459
+ readJson(path.join(roots.homeDir, '.pd', 'workbuddy-marketplace', 'principles-disciple', 'mcp-binding.json')),
460
+ 'workspaceDir',
461
+ );
462
+ if (wbBound !== undefined) claims.push({ host: 'workbuddy', workspaceDir: wbBound });
463
+ return claims;
464
+ }
465
+
466
+ /**
467
+ * Derive the Codex home from this launcher's own payload path:
468
+ * `<codexHome>/plugins/cache/<marketplace>/principles-disciple/<version>`.
469
+ * Returns null for any other layout (tests, OpenClaw/WorkBuddy payloads), so
470
+ * the persistent-binding lookup is inert where it does not apply.
471
+ */
472
+ function deriveCodexHomeFromPayload(root) {
473
+ const pluginDir = path.dirname(root);
474
+ const marketplaceDir = path.dirname(pluginDir);
475
+ const cacheDir = path.dirname(marketplaceDir);
476
+ const pluginsDir = path.dirname(cacheDir);
477
+ if (path.basename(pluginDir) !== 'principles-disciple') return null;
478
+ if (path.basename(cacheDir) !== 'cache' || path.basename(pluginsDir) !== 'plugins') return null;
479
+ const home = path.dirname(pluginsDir);
480
+ return path.isAbsolute(home) ? home : null;
481
+ }
482
+
483
+ /**
484
+ * PRI-1248: host-persistent binding candidates, in authority order. A Codex
485
+ * cache refresh deletes anything inside the versioned payload, so the copy in
486
+ * PLUGIN_DATA must be authoritative; the payload-local file stays as the
487
+ * legacy fallback for bindings written before this change.
488
+ */
489
+ function codexPersistentBindingCandidates(root) {
490
+ const candidates = [];
491
+ const pluginData = typeof process.env.PLUGIN_DATA === 'string' ? process.env.PLUGIN_DATA.trim() : '';
492
+ if (pluginData.length > 0 && path.isAbsolute(pluginData)) {
493
+ candidates.push(path.join(path.resolve(pluginData), 'mcp-binding.json'));
494
+ }
495
+ const codexHome = deriveCodexHomeFromPayload(root);
496
+ if (codexHome !== null) {
497
+ const marketplace = path.basename(path.dirname(path.dirname(root)));
498
+ const dataRoot = path.join(codexHome, 'plugins', 'data');
499
+ let matches = [];
500
+ try {
501
+ matches = fs.readdirSync(dataRoot).filter((name) => name.startsWith('principles-disciple-'));
502
+ } catch {
503
+ // First run before PLUGIN_DATA exists: fall through to the canonical name.
504
+ }
505
+ if (matches.length === 1) {
506
+ candidates.push(path.join(dataRoot, matches[0], 'mcp-binding.json'));
507
+ } else if (/^[A-Za-z0-9._-]+$/.test(marketplace)) {
508
+ candidates.push(path.join(dataRoot, `principles-disciple-${marketplace}`, 'mcp-binding.json'));
509
+ }
510
+ }
511
+ return [...new Set(candidates)];
512
+ }
513
+
357
514
  const PD_CONFIG_FILENAME = 'principles-disciple.json';
358
515
 
359
- /** A declared workspace must be one fixed, real directory — never HOME or a drive root. */
360
- function isUsableWorkspaceDir(candidate) {
516
+ /**
517
+ * Resolve the same effective host roots as PD Home. The launcher is a
518
+ * dependency-free CJS payload, so this small boundary mirrors the resolver's
519
+ * environment precedence and experiment containment rather than importing
520
+ * the ESM install-layout package.
521
+ */
522
+ function resolveHostConfigOverride(name, fallback, experimentRoot) {
523
+ const raw = typeof process.env[name] === 'string' ? process.env[name].trim() : '';
524
+ if (name === 'OPENCLAW_STATE_DIR' && raw !== '' && !path.isAbsolute(raw)) {
525
+ fail('openclaw_state_dir_not_absolute', 'OPENCLAW_STATE_DIR must be an absolute path.');
526
+ }
527
+ // The DEFAULT host dir must satisfy the same experiment containment as an
528
+ // override: a `<PD_EXPERIMENT_ROOT>/.openclaw` that is itself a link into
529
+ // production must be refused, never returned unchecked just because no
530
+ // override env var is set.
531
+ const candidate = raw !== '' ? raw : fallback;
532
+ if (experimentRoot !== null) {
533
+ if (!path.isAbsolute(candidate)) {
534
+ fail('experiment_host_config_invalid', `${name} host dir must be an absolute path inside PD_EXPERIMENT_ROOT (got "${candidate}").`);
535
+ }
536
+ if (!isInsideOrSame(experimentRoot, canonicalExisting(path.resolve(candidate)))) {
537
+ fail('experiment_host_config_invalid', `${name} host dir resolves outside PD_EXPERIMENT_ROOT; refusing to inspect or serve another host's production state.`);
538
+ }
539
+ }
540
+ return path.resolve(candidate);
541
+ }
542
+
543
+ /**
544
+ * HOME-first real-user-home resolution, mirroring the shared resolver's
545
+ * `resolveRealUserHome()` (install-layout): an explicit non-empty HOME wins,
546
+ * `os.homedir()` is the fallback. `os.homedir()` alone would ignore a sandboxed
547
+ * HOME on Windows (the OS home there ignores a sandboxed HOME) and diverge
548
+ * from the installer.
549
+ */
550
+ function resolveRealUserHomeLikeSharedResolver() {
551
+ const home = typeof process.env.HOME === 'string' ? process.env.HOME.trim() : '';
552
+ return home !== '' ? path.resolve(home) : path.resolve(os.homedir());
553
+ }
554
+
555
+ function resolveHostRoots(host, pluginRoot) {
556
+ const experimentRoot = EXPERIMENT_ROOT === '' ? null : experimentRootRealPath();
557
+ const homeDir = experimentRoot ?? resolveRealUserHomeLikeSharedResolver();
558
+ const stateDir = typeof process.env.OPENCLAW_STATE_DIR === 'string' ? process.env.OPENCLAW_STATE_DIR.trim() : '';
559
+ const openclawHome = stateDir !== ''
560
+ ? resolveHostConfigOverride('OPENCLAW_STATE_DIR', path.join(homeDir, '.openclaw'), experimentRoot)
561
+ : resolveHostConfigOverride('OPENCLAW_HOME', path.join(homeDir, '.openclaw'), experimentRoot);
562
+ const codexHomeFromPayload = host === 'codex' ? deriveCodexHomeFromPayload(pluginRoot) : null;
563
+ const codexHome = resolveHostConfigOverride('CODEX_HOME', codexHomeFromPayload ?? path.join(homeDir, '.codex'), experimentRoot);
564
+ const workbuddyConfigDir = resolveHostConfigOverride('WORKBUDDY_CONFIG_DIR', path.join(homeDir, '.workbuddy'), experimentRoot);
565
+ return { homeDir, openclawHome, codexHome, workbuddyConfigDir };
566
+ }
567
+
568
+ /** A declared workspace must be one fixed, real directory — never the effective HOME or a drive root. */
569
+ function isUsableWorkspaceDir(candidate, homeDir) {
361
570
  if (typeof candidate !== 'string' || candidate.length === 0 || !path.isAbsolute(candidate)) return false;
362
571
  const resolved = path.resolve(candidate);
363
- if (samePath(resolved, os.homedir())) return false;
572
+ if (samePath(resolved, homeDir)) return false;
364
573
  if (samePath(resolved, path.parse(resolved).root)) return false;
365
574
  try {
366
575
  return fs.statSync(resolved).isDirectory();
@@ -399,14 +608,13 @@ function readConfigWorkspace(files) {
399
608
  * inference: those describe where a session runs, not which state tree owns
400
609
  * governance for every agent of the host (SPEC §3.5).
401
610
  */
402
- function resolveDeclaredWorkspaceDir() {
403
- const home = os.homedir();
611
+ function resolveDeclaredWorkspaceDir(roots) {
404
612
  const readers = [
405
613
  () => process.env.PD_WORKSPACE_DIR,
406
614
  () => process.env.OPENCLAW_WORKSPACE,
407
615
  () => readConfigWorkspace([
408
- path.join(home, '.openclaw', PD_CONFIG_FILENAME),
409
- path.join(home, '.principles', PD_CONFIG_FILENAME),
616
+ path.join(roots.openclawHome, PD_CONFIG_FILENAME),
617
+ path.join(roots.homeDir, '.principles', PD_CONFIG_FILENAME),
410
618
  ]),
411
619
  ];
412
620
  let sawDeclaration = false;
@@ -419,7 +627,7 @@ function resolveDeclaredWorkspaceDir() {
419
627
  }
420
628
  if (typeof value !== 'string' || value.trim().length === 0) continue;
421
629
  sawDeclaration = true;
422
- if (isUsableWorkspaceDir(value.trim())) return { workspaceDir: path.resolve(value.trim()) };
630
+ if (isUsableWorkspaceDir(value.trim(), roots.homeDir)) return { workspaceDir: path.resolve(value.trim()) };
423
631
  }
424
632
  return { reason: sawDeclaration ? 'workspace_declaration_invalid' : 'workspace_declaration_missing' };
425
633
  }
@@ -445,14 +653,39 @@ if (detectedHosts.length !== 1) {
445
653
  }
446
654
  const host = detectedHosts[0];
447
655
  logState.host = host;
656
+ const hostRoots = resolveHostRoots(host, pluginRoot);
448
657
 
449
658
  // rc-1/rc-3/rc-5: the binding file is read as untrusted; every field is
450
659
  // validated before use and unknown content is never coerced.
451
- const bindingPath = path.join(pluginRoot, 'mcp-binding.json');
452
- try {
453
- logState.bindingPathExists = fs.statSync(bindingPath).isFile();
454
- } catch {
455
- logState.bindingPathExists = false;
660
+ // PRI-1248: a Codex payload directory is replaceable, so the host-persistent
661
+ // copy in PLUGIN_DATA is authoritative; the payload-local file remains the
662
+ // legacy fallback for bindings written before the durable location existed.
663
+ const legacyBindingPath = path.join(pluginRoot, 'mcp-binding.json');
664
+ const bindingCandidates = host === 'codex'
665
+ ? [...codexPersistentBindingCandidates(pluginRoot), legacyBindingPath]
666
+ : [legacyBindingPath];
667
+ let bindingPath = null;
668
+ for (const candidate of bindingCandidates) {
669
+ try {
670
+ if (fs.statSync(candidate).isFile()) {
671
+ bindingPath = candidate;
672
+ break;
673
+ }
674
+ } catch {
675
+ // Absent candidate — try the next location.
676
+ }
677
+ }
678
+ logState.bindingPathExists = bindingPath !== null;
679
+ logState.bindingSource = bindingPath === null
680
+ ? 'missing'
681
+ : (bindingPath === legacyBindingPath ? 'payload' : 'persistent');
682
+ if (bindingPath === null) {
683
+ fail(
684
+ 'binding_missing',
685
+ host === 'codex'
686
+ ? `Re-run the PD host setup (Codex: $pd-control setup) so mcp-binding.json is written for this host (checked ${bindingCandidates.join(' and ')}).`
687
+ : 'Re-run the PD host setup (Codex: $pd-control setup) so mcp-binding.json is written into the plugin directory.',
688
+ );
456
689
  }
457
690
  let raw;
458
691
  try {
@@ -568,6 +801,23 @@ if (!workspaceStat.isDirectory()) {
568
801
  }
569
802
  logState.workspaceResolution = 'ok';
570
803
 
804
+ // PRI-1247: "exists and is a directory" is not ownership. A binding left by
805
+ // the old OpenClaw-oriented detection points Codex at OpenClaw's governance
806
+ // tree, so pain evidence would land in the wrong database. Refuse that before
807
+ // any MCP traffic; the OpenClaw declaration gate below is unchanged.
808
+ // Directory SOURCES are the #2699 PD-Home roots authority only (payload/env
809
+ // Codex-home derivation already lives inside resolveHostRoots) — this check
810
+ // adds ownership VERDICT semantics (declarations, payload bindings, canonical
811
+ // identity, multi-owner report), never a second layout source.
812
+ const foreignWorkspaceOwners = findForeignWorkspaceOwner(host, binding.workspaceDir, hostRoots);
813
+ if (foreignWorkspaceOwners.length > 0) {
814
+ const owners = foreignWorkspaceOwners.join(',');
815
+ fail(
816
+ `binding_workspace_foreign_host:${owners}`,
817
+ `mcp-binding.json binds a workspace owned by ${owners} (default tree, formal declaration or payload binding). Re-run the PD host setup for ${host} with ITS OWN workspace (or an explicit supported --workspace), so pain evidence is not written into another host's database.`,
818
+ );
819
+ }
820
+
571
821
  // P0 (2026-11-13): an experiment must never bind a workspace outside its own
572
822
  // root. The binding is untrusted input written by another process generation;
573
823
  // a stale one (or one produced from an inherited production pointer) keeps the
@@ -592,7 +842,7 @@ if (EXPERIMENT_ROOT !== '') {
592
842
  // evidence to another agent. Codex/WorkBuddy have a single user-level workspace
593
843
  // and their binding writer is the authority; the gate is OpenClaw-only.
594
844
  if (host === 'openclaw') {
595
- const declared = resolveDeclaredWorkspaceDir();
845
+ const declared = resolveDeclaredWorkspaceDir(hostRoots);
596
846
  if (declared.workspaceDir === undefined) {
597
847
  fail(
598
848
  declared.reason,
@@ -622,6 +872,7 @@ writeLogEvent('info', 'launcher_start', {
622
872
  launcherVersion: LAUNCHER_VERSION,
623
873
  mcpServerVersion: packageManifest.version,
624
874
  bindingPathExists: logState.bindingPathExists,
875
+ bindingSource: logState.bindingSource,
625
876
  workspaceResolution: logState.workspaceResolution,
626
877
  envPresence: INITIAL_ENV_PRESENCE,
627
878
  });