@principles/workbuddy-adapter 0.6.7 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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, createHostIntentDocReader, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
35
+ import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, 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';
@@ -169,6 +169,12 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
169
169
  // for governance-admitted WorkBuddy pains — the neutral host reader
170
170
  // must ride along (flag-off = zero filesystem access inside it).
171
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 }),
175
+ // SPEC §9.6: lazy probe — a revoked flag stops persisted
176
+ // automatic_hook tasks at the bridge's execution boundary.
177
+ isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
172
178
  });
173
179
  const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
174
180
  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.7",
3
+ "version": "0.7.1",
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.10.1",
46
- "@principles/host-runtime": "^4.4.0",
47
- "@principles/install-layout": "^0.8.3"
45
+ "@principles/core": "^8.0.1",
46
+ "@principles/host-runtime": "^4.5.1",
47
+ "@principles/install-layout": "^0.9.1"
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": "57948395d8f4c8763027b95dd3e9463cba846bce"
64
+ "gitHead": "44eb2260606776dc28939a45d5375c2fb29b4a0c"
65
65
  }
@@ -359,32 +359,144 @@ function isInside(parent, child) {
359
359
  // governance workspace (the Codex installer used to inherit the OpenClaw
360
360
  // detection result). This mirrors `findForeignWorkspaceHost` in
361
361
  // @principles/install-layout; the parity test pins both sides together.
362
- function hostOwnedWorkspaces(bindingHost, homeDir, codexHome) {
362
+ function hostOwnedWorkspaces(bindingHost, roots) {
363
363
  switch (bindingHost) {
364
364
  case 'openclaw':
365
- return [path.join(homeDir, 'clawd'), path.join(homeDir, '.openclaw', 'workspace')];
365
+ return [path.join(roots.homeDir, 'clawd'), path.join(roots.openclawHome, 'workspace')];
366
366
  case 'codex':
367
- return [path.join(codexHome, 'pd-workspace')];
367
+ return [path.join(roots.codexHome, 'pd-workspace')];
368
368
  case 'workbuddy':
369
- return [path.join(homeDir, '.workbuddy', 'pd-workspace')];
369
+ return [path.join(roots.workbuddyConfigDir, 'pd-workspace')];
370
370
  default:
371
371
  return [];
372
372
  }
373
373
  }
374
374
 
375
- function findForeignWorkspaceOwner(bindingHost, workspaceDir, homeDir, codexHome) {
376
- const normalize = (value) => {
377
- const resolved = path.resolve(value);
378
- return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
379
- };
380
- const target = normalize(workspaceDir);
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); };
381
384
  for (const other of KNOWN_HOSTS) {
382
385
  if (other === bindingHost) continue;
383
- for (const owned of hostOwnedWorkspaces(other, homeDir, codexHome)) {
384
- if (isInsideOrSame(normalize(owned), target)) return other;
386
+ for (const owned of hostOwnedWorkspaces(other, roots)) {
387
+ if (isInsideOrSame(canonicalDirIdentity(owned), target)) claim(other);
385
388
  }
386
389
  }
387
- return null;
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
+ /**
439
+ * Read the workspaceDir of another host's persisted payload binding, but only
440
+ * when the binding passes the SAME full shape validation the launcher applies
441
+ * to its own binding (schemaVersion, host marker, absolute workspaceDir/
442
+ * runtimeDir/serverEntry, semver versions.mcpServer, canonical server entry).
443
+ * A binding that would fail launch-time validation cannot form a workspace
444
+ * claim — fail-closed, mirroring `readWorkspaceFromBinding` in
445
+ * @principles/install-layout.
446
+ */
447
+ function payloadBindingWorkspaceClaim(file, host) {
448
+ const parsed = readJson(file);
449
+ if (parsed === undefined) return undefined;
450
+ if (parsed.schemaVersion !== BINDING_SCHEMA) return undefined;
451
+ if (parsed.host !== host) return undefined;
452
+ if (typeof parsed.workspaceDir !== 'string' || !path.isAbsolute(parsed.workspaceDir.trim())) return undefined;
453
+ if (typeof parsed.runtimeDir !== 'string' || !path.isAbsolute(parsed.runtimeDir.trim())) return undefined;
454
+ if (typeof parsed.serverEntry !== 'string' || !path.isAbsolute(parsed.serverEntry.trim())) return undefined;
455
+ if (!isRecord(parsed.versions) || typeof parsed.versions.mcpServer !== 'string' || !SEMVER.test(parsed.versions.mcpServer)) return undefined;
456
+ // getCanonicalMcpServerEntry mirror: Codex uses the npm-dependency layout,
457
+ // the shared-runtime hosts the component layout.
458
+ const canonical = host === 'codex'
459
+ ? path.join(parsed.runtimeDir, 'node_modules', '@principles', 'pd-mcp-server', 'dist', 'index.js')
460
+ : path.join(parsed.runtimeDir, 'pd-mcp-server', 'dist', 'index.js');
461
+ if (!samePath(parsed.serverEntry, canonical)) return undefined;
462
+ return path.resolve(parsed.workspaceDir.trim());
463
+ }
464
+
465
+ function hostDeclaredWorkspaceClaims(roots) {
466
+ const claims = [];
467
+ const declarationFiles = [
468
+ path.join(roots.openclawHome, 'principles-disciple.json'),
469
+ path.join(roots.homeDir, '.principles', 'principles-disciple.json'),
470
+ ];
471
+ for (const file of declarationFiles) {
472
+ const declared = readAbsoluteWorkspaceField(readJson(file), 'workspace');
473
+ if (declared !== undefined) claims.push({ host: 'openclaw', workspaceDir: declared });
474
+ }
475
+ try {
476
+ const dataRoot = path.join(roots.codexHome, 'plugins', 'data');
477
+ for (const entry of fs.readdirSync(dataRoot)) {
478
+ if (typeof entry !== 'string' || !entry.startsWith('principles-disciple-')) continue;
479
+ const bound = payloadBindingWorkspaceClaim(path.join(dataRoot, entry, 'mcp-binding.json'), 'codex');
480
+ if (bound !== undefined) claims.push({ host: 'codex', workspaceDir: bound });
481
+ }
482
+ } catch {
483
+ // No Codex plugin data on this machine — nothing to claim.
484
+ }
485
+ const wbBound = payloadBindingWorkspaceClaim(
486
+ path.join(roots.homeDir, '.pd', 'workbuddy-marketplace', 'principles-disciple', 'mcp-binding.json'),
487
+ 'workbuddy',
488
+ );
489
+ if (wbBound !== undefined) claims.push({ host: 'workbuddy', workspaceDir: wbBound });
490
+ // P0-1: the OpenClaw plugin persists its own binding beside its installed
491
+ // extension (<openclawHome>/extensions/principles-disciple/mcp-binding.json).
492
+ // Without this read, a non-default workspace OpenClaw bound via
493
+ // PD_WORKSPACE_DIR/OPENCLAW_WORKSPACE was invisible to ownership checks.
494
+ const ocBound = payloadBindingWorkspaceClaim(
495
+ path.join(roots.openclawHome, 'extensions', 'principles-disciple', 'mcp-binding.json'),
496
+ 'openclaw',
497
+ );
498
+ if (ocBound !== undefined) claims.push({ host: 'openclaw', workspaceDir: ocBound });
499
+ return claims;
388
500
  }
389
501
 
390
502
  /**
@@ -437,11 +549,63 @@ function codexPersistentBindingCandidates(root) {
437
549
 
438
550
  const PD_CONFIG_FILENAME = 'principles-disciple.json';
439
551
 
440
- /** A declared workspace must be one fixed, real directory — never HOME or a drive root. */
441
- function isUsableWorkspaceDir(candidate) {
552
+ /**
553
+ * Resolve the same effective host roots as PD Home. The launcher is a
554
+ * dependency-free CJS payload, so this small boundary mirrors the resolver's
555
+ * environment precedence and experiment containment rather than importing
556
+ * the ESM install-layout package.
557
+ */
558
+ function resolveHostConfigOverride(name, fallback, experimentRoot) {
559
+ const raw = typeof process.env[name] === 'string' ? process.env[name].trim() : '';
560
+ if (name === 'OPENCLAW_STATE_DIR' && raw !== '' && !path.isAbsolute(raw)) {
561
+ fail('openclaw_state_dir_not_absolute', 'OPENCLAW_STATE_DIR must be an absolute path.');
562
+ }
563
+ // The DEFAULT host dir must satisfy the same experiment containment as an
564
+ // override: a `<PD_EXPERIMENT_ROOT>/.openclaw` that is itself a link into
565
+ // production must be refused, never returned unchecked just because no
566
+ // override env var is set.
567
+ const candidate = raw !== '' ? raw : fallback;
568
+ if (experimentRoot !== null) {
569
+ if (!path.isAbsolute(candidate)) {
570
+ fail('experiment_host_config_invalid', `${name} host dir must be an absolute path inside PD_EXPERIMENT_ROOT (got "${candidate}").`);
571
+ }
572
+ if (!isInsideOrSame(experimentRoot, canonicalExisting(path.resolve(candidate)))) {
573
+ fail('experiment_host_config_invalid', `${name} host dir resolves outside PD_EXPERIMENT_ROOT; refusing to inspect or serve another host's production state.`);
574
+ }
575
+ }
576
+ return path.resolve(candidate);
577
+ }
578
+
579
+ /**
580
+ * HOME-first real-user-home resolution, mirroring the shared resolver's
581
+ * `resolveRealUserHome()` (install-layout): an explicit non-empty HOME wins,
582
+ * `os.homedir()` is the fallback. `os.homedir()` alone would ignore a sandboxed
583
+ * HOME on Windows (the OS home there ignores a sandboxed HOME) and diverge
584
+ * from the installer.
585
+ */
586
+ function resolveRealUserHomeLikeSharedResolver() {
587
+ const home = typeof process.env.HOME === 'string' ? process.env.HOME.trim() : '';
588
+ return home !== '' ? path.resolve(home) : path.resolve(os.homedir());
589
+ }
590
+
591
+ function resolveHostRoots(host, pluginRoot) {
592
+ const experimentRoot = EXPERIMENT_ROOT === '' ? null : experimentRootRealPath();
593
+ const homeDir = experimentRoot ?? resolveRealUserHomeLikeSharedResolver();
594
+ const stateDir = typeof process.env.OPENCLAW_STATE_DIR === 'string' ? process.env.OPENCLAW_STATE_DIR.trim() : '';
595
+ const openclawHome = stateDir !== ''
596
+ ? resolveHostConfigOverride('OPENCLAW_STATE_DIR', path.join(homeDir, '.openclaw'), experimentRoot)
597
+ : resolveHostConfigOverride('OPENCLAW_HOME', path.join(homeDir, '.openclaw'), experimentRoot);
598
+ const codexHomeFromPayload = host === 'codex' ? deriveCodexHomeFromPayload(pluginRoot) : null;
599
+ const codexHome = resolveHostConfigOverride('CODEX_HOME', codexHomeFromPayload ?? path.join(homeDir, '.codex'), experimentRoot);
600
+ const workbuddyConfigDir = resolveHostConfigOverride('WORKBUDDY_CONFIG_DIR', path.join(homeDir, '.workbuddy'), experimentRoot);
601
+ return { homeDir, openclawHome, codexHome, workbuddyConfigDir };
602
+ }
603
+
604
+ /** A declared workspace must be one fixed, real directory — never the effective HOME or a drive root. */
605
+ function isUsableWorkspaceDir(candidate, homeDir) {
442
606
  if (typeof candidate !== 'string' || candidate.length === 0 || !path.isAbsolute(candidate)) return false;
443
607
  const resolved = path.resolve(candidate);
444
- if (samePath(resolved, os.homedir())) return false;
608
+ if (samePath(resolved, homeDir)) return false;
445
609
  if (samePath(resolved, path.parse(resolved).root)) return false;
446
610
  try {
447
611
  return fs.statSync(resolved).isDirectory();
@@ -480,14 +644,13 @@ function readConfigWorkspace(files) {
480
644
  * inference: those describe where a session runs, not which state tree owns
481
645
  * governance for every agent of the host (SPEC §3.5).
482
646
  */
483
- function resolveDeclaredWorkspaceDir() {
484
- const home = os.homedir();
647
+ function resolveDeclaredWorkspaceDir(roots) {
485
648
  const readers = [
486
649
  () => process.env.PD_WORKSPACE_DIR,
487
650
  () => process.env.OPENCLAW_WORKSPACE,
488
651
  () => readConfigWorkspace([
489
- path.join(home, '.openclaw', PD_CONFIG_FILENAME),
490
- path.join(home, '.principles', PD_CONFIG_FILENAME),
652
+ path.join(roots.openclawHome, PD_CONFIG_FILENAME),
653
+ path.join(roots.homeDir, '.principles', PD_CONFIG_FILENAME),
491
654
  ]),
492
655
  ];
493
656
  let sawDeclaration = false;
@@ -500,7 +663,7 @@ function resolveDeclaredWorkspaceDir() {
500
663
  }
501
664
  if (typeof value !== 'string' || value.trim().length === 0) continue;
502
665
  sawDeclaration = true;
503
- if (isUsableWorkspaceDir(value.trim())) return { workspaceDir: path.resolve(value.trim()) };
666
+ if (isUsableWorkspaceDir(value.trim(), roots.homeDir)) return { workspaceDir: path.resolve(value.trim()) };
504
667
  }
505
668
  return { reason: sawDeclaration ? 'workspace_declaration_invalid' : 'workspace_declaration_missing' };
506
669
  }
@@ -526,6 +689,7 @@ if (detectedHosts.length !== 1) {
526
689
  }
527
690
  const host = detectedHosts[0];
528
691
  logState.host = host;
692
+ const hostRoots = resolveHostRoots(host, pluginRoot);
529
693
 
530
694
  // rc-1/rc-3/rc-5: the binding file is read as untrusted; every field is
531
695
  // validated before use and unknown content is never coerced.
@@ -677,20 +841,16 @@ logState.workspaceResolution = 'ok';
677
841
  // the old OpenClaw-oriented detection points Codex at OpenClaw's governance
678
842
  // tree, so pain evidence would land in the wrong database. Refuse that before
679
843
  // any MCP traffic; the OpenClaw declaration gate below is unchanged.
680
- // The payload-derived Codex home is only meaningful when THIS payload is a
681
- // Codex payload: WorkBuddy/OpenClaw caches share the same
682
- // `<root>/plugins/cache/<marketplace>/principles-disciple/<version>` shape, and
683
- // deriving from them would invent a Codex workspace inside the host's own tree.
684
- const ownershipHome = os.homedir();
685
- const ownershipCodexHome = (host === 'codex' ? deriveCodexHomeFromPayload(pluginRoot) : null)
686
- ?? (typeof process.env.CODEX_HOME === 'string' && path.isAbsolute(process.env.CODEX_HOME)
687
- ? path.resolve(process.env.CODEX_HOME)
688
- : path.join(ownershipHome, '.codex'));
689
- const foreignWorkspaceHost = findForeignWorkspaceOwner(host, binding.workspaceDir, ownershipHome, ownershipCodexHome);
690
- if (foreignWorkspaceHost !== null) {
844
+ // Directory SOURCES are the #2699 PD-Home roots authority only (payload/env
845
+ // Codex-home derivation already lives inside resolveHostRoots) — this check
846
+ // adds ownership VERDICT semantics (declarations, payload bindings, canonical
847
+ // identity, multi-owner report), never a second layout source.
848
+ const foreignWorkspaceOwners = findForeignWorkspaceOwner(host, binding.workspaceDir, hostRoots);
849
+ if (foreignWorkspaceOwners.length > 0) {
850
+ const owners = foreignWorkspaceOwners.join(',');
691
851
  fail(
692
- `binding_workspace_foreign_host:${foreignWorkspaceHost}`,
693
- `mcp-binding.json binds ${foreignWorkspaceHost}'s default governance workspace. 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.`,
852
+ `binding_workspace_foreign_host:${owners}`,
853
+ `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.`,
694
854
  );
695
855
  }
696
856
 
@@ -718,7 +878,7 @@ if (EXPERIMENT_ROOT !== '') {
718
878
  // evidence to another agent. Codex/WorkBuddy have a single user-level workspace
719
879
  // and their binding writer is the authority; the gate is OpenClaw-only.
720
880
  if (host === 'openclaw') {
721
- const declared = resolveDeclaredWorkspaceDir();
881
+ const declared = resolveDeclaredWorkspaceDir(hostRoots);
722
882
  if (declared.workspaceDir === undefined) {
723
883
  fail(
724
884
  declared.reason,
@@ -7,11 +7,17 @@ description: 记录一条"相对锚点的显著行为背离"(Pain)。Owner
7
7
 
8
8
  # PD Pain Signal(WorkBuddy)
9
9
 
10
- Pain = 相对某个明确锚点的、具体的行为背离。三要素必须同时成立:
10
+ Pain 是定位和触发信号,不是数据集样本本体;样本单位是有完整上下文的行为偏差事件。必须在具体 Owner、任务和决策时点中,比较宿主行为与当时可证实的用户预期、意图及适用 PD 原则。任务成功仍可能偏离;任务失败也不自动意味着偏离。不得把“少询问、执行快、检查多”等行为风格当作普遍更好。
11
+
12
+ 完整事件需要关联原始相关对话轨迹、工具调用与返回、产物和状态变化;摘要不能替代原始轨迹。区分当时宿主有机会获知的期望、事后澄清和评价者推断。完整归档可以包含后续纠正,但不得将后续信息泄漏给更早的决策点评测。完整轨迹暂不可用时,不要因此丢弃合法 Pain:按现有授权入口保存可验证信号与来源线索,明确保留为不完整候选,不得宣称完整样本,也不得绕过留存授权补齐。
13
+
14
+ 规范详见 [PD 行为偏差事件与相对评价规范](https://github.com/csuzngjh/principles/blob/main/docs/concepts/PD_BEHAVIOR_DEVIATION_EVENT_AND_RELATIVE_EVALUATION.md)。当前提交接口仍要求一个主锚点;这是入口字段约束,不代表完整事件只包含一个期望依据。额外期望或原则冲突应在 reason 中如实保留。
15
+
16
+ 当前提交接口的主锚点仍需满足以下要求:
11
17
 
12
18
  1. **锚点** —— Owner 的明示要求、既有原则,或生效中的 Agent 指令 / Skill 要求。
13
19
  2. **具体行为** —— 你实际做了什么、漏了什么。
14
- 3. **显著背离** —— 相对该锚点可以说清楚的差距。
20
+ 3. **具体可说明的背离** —— 相对该锚点可以说清楚的差距;影响大小、重复次数和情绪强度不是提交门槛。
15
21
 
16
22
  没有证明影响、没有重复发生、Owner 之前没纠正过,都**不是**不提交的理由,只影响 Owner 的注意力排序。
17
23
 
@@ -76,6 +82,8 @@ Owner 说过 —— 本次对话、Owner 文档或已批准的决定。`anchorRe
76
82
 
77
83
  ## `reason` —— 六部分,按顺序
78
84
 
85
+ 以下六部分描述当前提交入口需要表达的主锚点,不等于完整事件的数据模型。完整事件中的事后澄清和评价者推断必须分开保存,不能冒充 Owner 原话或宿主当时已知的要求;只有推断不足以满足当前有锚点提交约束时,可以保留为待核验材料,不得伪装成已验证偏差。
86
+
79
87
  1. **锚点** —— 引用或指明(原则 id@version、指令 path#section、Owner 原话 + 出处)。
80
88
  2. **锚点来源与引用等级** —— `verbatim` / `paraphrase` / `recollection` / `inference`。不得抬高等级。仅有 `recollection` 或 `inference` 时不够:先与 Owner 确认原话。
81
89
  3. **观察到的行为** —— 具体动作、顺序、跳过的步骤、越界之处。不要写"质量不好"。