fuli-context 0.20.0-beta.13 → 0.20.0-beta.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/web/assets/{index-DvkJiX-L.js → index-GEnfRzSe.js} +1 -1
  2. package/dist/web/index.html +1 -1
  3. package/graph-provider/fuli_graph/app.py +16 -11
  4. package/graph-provider/fuli_graph/graph_query.py +30 -2
  5. package/graph-provider/fuli_graph/knowledge_audit.py +9 -1
  6. package/graph-provider/fuli_graph/knowledge_item_routes.py +10 -6
  7. package/graph-provider/fuli_graph/knowledge_item_view.py +41 -12
  8. package/graph-provider/fuli_graph/knowledge_item_view_models.py +3 -3
  9. package/graph-provider/fuli_graph/knowledge_review.py +47 -10
  10. package/graph-provider/fuli_graph/knowledge_search.py +18 -22
  11. package/graph-provider/fuli_graph/knowledge_session_migration.py +14 -4
  12. package/graph-provider/fuli_graph/knowledge_session_migration_models.py +2 -2
  13. package/graph-provider/fuli_graph/knowledge_tag_routes.py +7 -5
  14. package/graph-provider/fuli_graph/knowledge_tags.py +8 -4
  15. package/graph-provider/fuli_graph/knowledge_visibility.py +195 -0
  16. package/graph-provider/fuli_graph/models.py +12 -2
  17. package/graph-provider/fuli_graph/preference_conflicts.py +50 -4
  18. package/graph-provider/fuli_graph/publication_source_copies.py +36 -0
  19. package/graph-provider/fuli_graph/session_records.py +33 -13
  20. package/graph-provider/fuli_graph/session_records_models.py +4 -2
  21. package/graph-provider/fuli_graph/store_knowledge.py +5 -1
  22. package/graph-provider/fuli_graph/store_publication.py +70 -12
  23. package/graph-provider/pyproject.toml +1 -1
  24. package/native/win32/fuli-win-helper.exe +0 -0
  25. package/npm-shrinkwrap.json +2 -2
  26. package/package.json +1 -1
  27. package/skills/capturing-session-knowledge/references/retrieval.md +6 -0
  28. package/src/agent-tools/graph-definitions.js +4 -4
  29. package/src/agent-tools/interface-definitions.js +2 -1
  30. package/src/agent-tools/session-fuli-gate.js +55 -26
  31. package/src/agent-tools.js +2 -4
  32. package/src/agents/claude-code/lifecycle-hook.js +4 -3
  33. package/src/agents/codex/lifecycle-hook.js +4 -3
  34. package/src/agents/lifecycle-message.js +18 -0
  35. package/src/agents/turn-receipt.js +15 -8
  36. package/src/app/agent-request-context.js +18 -0
  37. package/src/graphiti/capture-notice.js +4 -1
  38. package/src/graphiti/federated-application.js +49 -60
  39. package/src/graphiti/human-review-channel.js +9 -5
  40. package/src/graphiti/knowledge-item-edit.js +7 -4
  41. package/src/graphiti/knowledge-reader.js +46 -0
  42. package/src/graphiti/knowledge-result-budget.js +63 -12
  43. package/src/graphiti/knowledge-tags.js +12 -1
  44. package/src/graphiti/provider-client.js +13 -21
  45. package/src/graphiti/publication-draft-capture.js +28 -0
  46. package/src/graphiti/session-knowledge-migration.js +7 -3
  47. package/src/graphiti/session-layer-decision.js +28 -6
  48. package/src/graphiti/session-records.js +26 -15
  49. package/src/graphiti/turn-receipt-delivery.js +5 -2
  50. package/src/graphiti/writing-taste-profile-workflow.js +13 -7
  51. package/src/http/api-router.js +2 -1
  52. package/src/http/graph-api-router.js +13 -10
  53. package/src/http/knowledge-item-api-router.js +17 -4
  54. package/src/http/knowledge-tags-api-router.js +21 -9
  55. package/src/http/session-records-api-router.js +7 -3
  56. package/src/knowledge-owner-reads/console-port.js +51 -0
  57. package/src/knowledge-tags/console-port.js +3 -2
  58. package/src/mcp/preference-delivery.js +7 -4
  59. package/src/mcp/provider-task-context-registry.js +15 -0
  60. package/src/mcp/tool-result.js +3 -3
  61. package/src/presence/windows-helper-pin.js +1 -1
  62. package/src/server.js +8 -1
@@ -15,19 +15,43 @@ from .models import (
15
15
  SubscriptionRecord,
16
16
  )
17
17
  from .provider_values import json_object, native_datetime, now_utc, stable_uuid
18
- from .publication_source_copies import publication_source_identity
18
+ from .publication_source_copies import PLAIN, PROJECT_AGENT, draft_sources, publication_source_identity
19
19
  from .knowledge_source_fence import require_source_available
20
20
  from .knowledge_versions import lock_knowledge
21
21
  from .store_transactions import query_store_transaction
22
22
  from .publication_submission import decide_submission
23
23
  from .publication_submission_models import PublicationSubmissionDecision
24
24
 
25
+ # An FLA's own knowledge stays in the personal graph; Node refuses to queue it
26
+ # for a team project and so does the Provider (0.20.1).
27
+ _PROJECT_AGENT_KNOWLEDGE = {'code': 'project_agent_knowledge_personal_only',
28
+ 'message': 'Project Agent knowledge can only be captured in the personal graph'}
29
+
30
+
31
+ def _draft_identity(space, draft) -> dict:
32
+ """A stored draft's source identity; older drafts derive it from the payload."""
33
+ return {**publication_source_identity(space['group_id'], json_object(draft.get('payload'))),
34
+ **json_object(draft.get('source_identity'))}
35
+
25
36
 
26
37
  class StorePublication:
38
+ async def _project_agent_drafts(self, actor, space, drafts) -> set[int]:
39
+ """The positions among these drafts a reader without the human-review
40
+ proof may not see: every one whose source is not positively plain
41
+ work. A draft of an FLA's work (made before the Provider refused them),
42
+ and one whose source is erased or was never recorded here, is the
43
+ person's alone, its body, source and submission metadata alike; the
44
+ console's port lists, reads, submits and settles it."""
45
+ if actor.get('_human_review_verified') is True:
46
+ return set()
47
+ owners = await draft_sources(self, space, [_draft_identity(space, draft) for draft in drafts])
48
+ return {index for index, owner in enumerate(owners) if owner != PLAIN}
49
+
27
50
  async def decide_publication_submission(self, actor, personal_space_id, draft_id, decision):
28
51
  """Internal submission protocol; every transition serializes with erasure."""
29
52
  self._require_personal()
30
53
  space = await self.authorize(actor, personal_space_id, 'maintainer')
54
+ await self._refuse_project_agent_draft(actor, space, draft_id, decision.decision)
31
55
  refusal = None
32
56
  async with query_store_transaction(self) as scoped:
33
57
  await lock_knowledge(scoped, space)
@@ -62,9 +86,13 @@ class StorePublication:
62
86
  await require_source_available(scoped, space, episode_id=identity.get('episode_id'),
63
87
  source_application=identity.get('source_application'), session_id=identity.get('session_id'),
64
88
  source_turn_id=identity.get('source_turn_id'))
89
+ if (await draft_sources(scoped, space, [identity])) == [PROJECT_AGENT]:
90
+ raise HTTPException(status_code=422, detail=_PROJECT_AGENT_KNOWLEDGE)
65
91
  records, _, _ = await scoped.runtime.driver.execute_query(
66
92
  '''
67
93
  MATCH (space:FuliSpace {id: $personal_space_id, kind: 'personal'})
94
+ OPTIONAL MATCH (stored:FuliPublicationDraft {id: $id})
95
+ WITH space, stored IS NOT NULL AS existed
68
96
  MERGE (draft:FuliPublicationDraft {id: $id})
69
97
  ON CREATE SET draft.personal_space_id = $personal_space_id,
70
98
  draft.target_project_id = $target_project_id,
@@ -74,7 +102,7 @@ class StorePublication:
74
102
  draft.source_identity = $source_identity,
75
103
  draft.created_at = $created_at
76
104
  MERGE (space)-[:HAS_PUBLICATION_DRAFT]->(draft)
77
- RETURN draft
105
+ RETURN draft, existed
78
106
  ''',
79
107
  personal_space_id=request.personal_space_id,
80
108
  id=draft_id,
@@ -84,7 +112,14 @@ class StorePublication:
84
112
  source_identity=json.dumps(identity, sort_keys=True, separators=(',', ':')),
85
113
  created_at=created_at,
86
114
  )
87
- return self._publication_draft(records[0]['draft'])
115
+ draft = dict(records[0]['draft'])
116
+ # A retry of a key already drafted gets the stored draft back unchanged, so it is judged by
117
+ # the STORED row's provenance, not the request's. One this caller may not read is answered
118
+ # exactly as a draft that does not exist, whatever the request claims about its source: a
119
+ # self-reported identity is no proof that it is the same create (0.20.1).
120
+ if records[0]['existed'] and await self._project_agent_drafts(actor, space, [draft]):
121
+ raise HTTPException(status_code=404, detail='publication draft not found')
122
+ return self._publication_draft(draft)
88
123
 
89
124
  async def list_publication_drafts(
90
125
  self,
@@ -107,10 +142,11 @@ class StorePublication:
107
142
  status=draft_status,
108
143
  routing_='r',
109
144
  )
110
- return [self._publication_draft({**dict(record['draft']), 'source_identity': json.dumps({
111
- **publication_source_identity(space['group_id'], json_object(record['draft'].get('payload'))),
112
- **json_object(record['draft'].get('source_identity'))})}, metadata_only=metadata_only)
113
- for record in records]
145
+ drafts = [dict(record['draft']) for record in records]
146
+ hidden = await self._project_agent_drafts(actor, space, drafts)
147
+ return [self._publication_draft({**draft, 'source_identity': json.dumps(_draft_identity(space, draft))},
148
+ metadata_only=metadata_only)
149
+ for index, draft in enumerate(drafts) if index not in hidden]
114
150
 
115
151
  async def get_publication_draft(
116
152
  self,
@@ -119,7 +155,30 @@ class StorePublication:
119
155
  draft_id: str,
120
156
  ) -> PublicationDraftRecord:
121
157
  self._require_personal()
122
- await self.authorize(actor, personal_space_id, 'reader')
158
+ space = await self.authorize(actor, personal_space_id, 'reader')
159
+ draft = await self._stored_draft(space, draft_id)
160
+ if draft is None or await self._project_agent_drafts(actor, space, [draft]):
161
+ raise HTTPException(status_code=404, detail='publication draft not found')
162
+ return self._publication_draft(draft)
163
+
164
+ async def _refuse_project_agent_draft(self, actor, space, draft_id, decision: str) -> None:
165
+ """A decision on a draft whose source is not positively plain work: to
166
+ a caller without the human-review proof it does not exist, so no reply
167
+ carries its body, source or attempt. The person's console decides it;
168
+ a draft of an FLA's work it settles, keeps or ignores, but never starts
169
+ publishing. A missing draft is left to the decision's own answer."""
170
+ draft = await self._stored_draft(space, draft_id)
171
+ if draft is None:
172
+ return
173
+ [owner] = await draft_sources(self, space, [_draft_identity(space, draft)])
174
+ if owner == PLAIN:
175
+ return
176
+ if actor.get('_human_review_verified') is not True:
177
+ raise HTTPException(status_code=404, detail='publication draft not found')
178
+ if owner == PROJECT_AGENT and decision == 'begin_submit_public':
179
+ raise HTTPException(status_code=422, detail=_PROJECT_AGENT_KNOWLEDGE)
180
+
181
+ async def _stored_draft(self, space, draft_id) -> dict | None:
123
182
  records, _, _ = await self.runtime.driver.execute_query(
124
183
  '''
125
184
  MATCH (:FuliSpace {id: $personal_space_id, kind: 'personal'})-
@@ -127,13 +186,11 @@ class StorePublication:
127
186
  (draft:FuliPublicationDraft {id: $draft_id})
128
187
  RETURN draft
129
188
  ''',
130
- personal_space_id=personal_space_id,
189
+ personal_space_id=space['id'],
131
190
  draft_id=draft_id,
132
191
  routing_='r',
133
192
  )
134
- if not records:
135
- raise HTTPException(status_code=404, detail='publication draft not found')
136
- return self._publication_draft(records[0]['draft'])
193
+ return dict(records[0]['draft']) if records else None
137
194
 
138
195
  async def decide_publication_draft(
139
196
  self,
@@ -146,6 +203,7 @@ class StorePublication:
146
203
  return await self.decide_publication_submission(actor, personal_space_id, draft_id, decision)
147
204
  self._require_personal()
148
205
  space = await self.authorize(actor, personal_space_id, 'maintainer')
206
+ await self._refuse_project_agent_draft(actor, space, draft_id, decision.decision)
149
207
  records, _, _ = await self.runtime.driver.execute_query(
150
208
  '''
151
209
  MATCH (:FuliSpace {id: $personal_space_id, kind: 'personal'})-
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fuli-graph-provider"
3
- version = "0.20.0b13"
3
+ version = "0.20.0b15"
4
4
  description = "Graphiti-backed personal and shared project provider for Fuli."
5
5
  requires-python = ">=3.12"
6
6
  dependencies = [
Binary file
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "fuli-context",
3
- "version": "0.20.0-beta.13",
3
+ "version": "0.20.0-beta.15",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "fuli-context",
9
- "version": "0.20.0-beta.13",
9
+ "version": "0.20.0-beta.15",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@a2a-js/sdk": "1.3.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fuli-context",
3
- "version": "0.20.0-beta.13",
3
+ "version": "0.20.0-beta.15",
4
4
  "description": "Local-first collaboration relationship graph for AI agents.",
5
5
  "type": "module",
6
6
  "files": [
@@ -33,6 +33,12 @@ identifier, and likely runbook category. Never pass the full conversational requ
33
33
  query. For example, a version-release request should search release/publish and push/commit
34
34
  runbook concepts separately instead of searching the entire sentence.
35
35
 
36
+ Its response states `retrievalGuidance`, `noMatchSourceMarker` and the shared scope fields once
37
+ at the top level; each entry in `results` keeps its own `query`, records and `sourceMarker`. On a
38
+ bounded page (`next_cursor` present), a query with nothing on that page shows only `query` and
39
+ `total_items`; its records arrive on a later page. Long project ID lists name a prefix and count
40
+ the rest in `project_ids_omitted`.
41
+
36
42
  Pending knowledge is eligible for on-demand retrieval and must remain visibly marked.
37
43
  `agent_confirmed` knowledge is usable but ranks below user or authoritative-source
38
44
  confirmation.
@@ -383,9 +383,9 @@ export const GRAPH_TOOL_DEFINITIONS = [
383
383
  },
384
384
  {
385
385
  name: 'resolve_deferred_preference_conflict',
386
- description: 'Resolve one AI-deferred conflict from get_collaboration_preferences only when the current task needs that preference. Compare both confirmed sides with their evidence and current context before choosing. Updates effective knowledge, preserves revision history, and permanently marks prior conflict as resolved by AI. Use merge with canonical item and merged instruction, keep_left/keep_right to retain one side, or split_scope to move one side to an exact personal project.',
386
+ description: 'Resolve one AI-deferred conflict from get_collaboration_preferences only when the current task needs that preference. Compare both confirmed sides with their evidence and current context before choosing. Updates effective knowledge, preserves revision history, and permanently marks prior conflict as resolved by AI. Use merge with canonical item and merged instruction, keep_left/keep_right to retain one side, or split_scope to move one side to an exact personal project. An FLA names projectAgentId and personalProjectId.',
387
387
  inputSchema: objectSchema({
388
- personalSpaceId: id,
388
+ personalSpaceId: id, personalProjectId: nullableStringSchema(), projectAgentId: nullableStringSchema(),
389
389
  conflictId: boundedString(1024),
390
390
  resolution: enumSchema([
391
391
  'merge', 'keep_left', 'keep_right', 'split_scope'
@@ -621,11 +621,11 @@ export const GRAPH_TOOL_DEFINITIONS = [
621
621
  },
622
622
  {
623
623
  name: 'get_knowledge_graph',
624
- description: 'Return a bounded node-edge graph for a personal space, one exact local personal project, or a team-shared project.',
624
+ description: 'Return a bounded node-edge graph for a personal space, one exact local personal project, or a team-shared project. An FLA sees its own knowledge only with projectAgentId and personalProjectId.',
625
625
  inputSchema: objectSchema({
626
626
  spaceId: id,
627
627
  providerUrl: nullableStringSchema(),
628
- personalProjectId: nullableStringSchema(),
628
+ personalProjectId: nullableStringSchema(), projectAgentId: nullableStringSchema(),
629
629
  limit: integerSchema({ minimum: 1, maximum: 2000 })
630
630
  }, ['spaceId'])
631
631
  },
@@ -184,9 +184,10 @@ export const AGENT_INTERFACE_DEFINITIONS = [
184
184
  {
185
185
  name: 'defer_preference_conflict',
186
186
  title: 'WRITE · Defer preference conflict',
187
- description: 'Defer one exact preference conflict without resolving either side. The conflict remains visible for later review.',
187
+ description: 'Defer one exact preference conflict without resolving either side. The conflict remains visible for later review. An FLA names projectAgentId and personalProjectId.',
188
188
  inputSchema: objectSchema({
189
189
  personalSpaceId: id,
190
+ personalProjectId: nullableStringSchema(), projectAgentId: nullableStringSchema(),
190
191
  conflictId: { ...stringSchema(), minLength: 1, maxLength: 1024 },
191
192
  preferenceKey: label,
192
193
  preferenceScope: enumSchema(['global', 'project']),
@@ -1,6 +1,6 @@
1
- import { sessionsMayBeOff, sessionUseDecision } from '../graphiti/session-layer-decision.js';
1
+ import { sessionsMayBeOff, sessionsMayBeWithoutCapture, sessionUseDecision } from '../graphiti/session-layer-decision.js';
2
2
  import { captureNotice } from '../graphiti/capture-notice.js';
3
- import { activeAgentHostClient } from '../app/agent-request-context.js';
3
+ import { activeAgentHostClient, runWithTaskBoundSession } from '../app/agent-request-context.js';
4
4
 
5
5
  // What an Agent may still call for a session FULI is off for (rec#5 C3b).
6
6
  // Every other tool returns stored memory or preferences to the model (entry,
@@ -19,18 +19,22 @@ const OPEN_TOOLS = new Set([
19
19
  'acquire_runtime_lease', 'refresh_runtime_lease', 'release_runtime_lease'
20
20
  ]);
21
21
  export const SESSION_FULI_OFF = 'fuli_off';
22
- // Tools an Agent calls without a task of their own (entry, recall, team and
23
- // judgment reads). They take the current taskContextToken only to say which
24
- // session they are for: without it, a call is refused while any session of
25
- // its client is off, since no host session shows the current one (option Y,
26
- // #251). The token is used here and never reaches the tool.
22
+ // Tools whose own schema names no task: those an Agent calls without a task of
23
+ // their own (entry, recall, team and judgment reads) and the records a task
24
+ // writes as it goes or closes. They take the current taskContextToken only to
25
+ // say which session they are for: without it, a call is refused while any
26
+ // session of its client is off, since no host session shows the current one
27
+ // (option Y, #251). The token is used here and never reaches the tool.
27
28
  const ATTRIBUTED_TOOLS = new Set([
28
29
  'get_collaboration_preferences', 'get_user_taste_skill', 'search_current_project_knowledge', 'search_knowledge_graph',
29
30
  'search_connected_knowledge', 'list_project_agents', 'get_project_agent_context', 'get_project_agent_memory',
30
31
  'list_preference_conflicts', 'resolve_deferred_preference_conflict', 'request_agent_attention', 'assess_agent_action',
31
- 'review_with_tonborg', 'get_agent_quality_gate', 'get_project_team', 'recommend_next_workflow_steps', 'find_agents'
32
+ 'review_with_tonborg', 'get_agent_quality_gate', 'get_project_team', 'recommend_next_workflow_steps', 'find_agents',
33
+ 'capture_session_knowledge', 'record_decision_trace', 'record_workflow_transition_observation',
34
+ 'checkpoint_project_agent_memory', 'record_project_agent_task_activity', 'record_project_agent_executor_actual',
35
+ 'record_project_agent_task_outcome'
32
36
  ]);
33
- // Bare: a value the registry does not know only leaves the call unattributed.
37
+ // Bare: a value that is not a current task token only leaves the call without a session.
34
38
  const TOKEN_FIELD = Object.freeze({ type: 'string' });
35
39
 
36
40
  // A tool definition as Agents see it: an attributed tool lists the token.
@@ -46,36 +50,61 @@ export function withoutSessionAttribution(name, input) {
46
50
  return rest;
47
51
  }
48
52
  const GUIDANCE = 'FULI is off for this session, so nothing was read, injected, recorded or started. Do not call FULI tools for this session or add an agent_receipt; only the person can turn it on (/fuli start).';
49
- const UNATTRIBUTED_GUIDANCE = 'FULI could not tell which session this call comes from while a session of this client has FULI off, so nothing was read or started. Calls that carry the current taskContextToken of this session are served; do not describe this as the person stopping FULI here.';
53
+ // The refusals that are not the person turning FULI off here.
54
+ const REASON_GUIDANCE = Object.freeze({
55
+ session_unattributed: 'FULI could not tell which session this call comes from while a session of this client has FULI off, so nothing was read or started. Calls that carry the current taskContextToken of this session are served; do not describe this as the person stopping FULI here.',
56
+ // Every prompt, a "continue" included, begins a new task; only a session's
57
+ // current task can be checkpointed (store_task_contexts.py).
58
+ task_token_not_current: 'This call\'s taskContextToken is not the current task of its session (each new prompt, a "continue" included, begins a new task with a new token; a token of another client or one FULI never issued looks the same), and a session of this client has FULI off, so nothing was read, recorded or started. Retry with the taskContextToken from this turn\'s FULI context. Do not try to checkpoint or record the earlier task: a task that is no longer current cannot be checkpointed. Do not describe this as the person stopping FULI here.',
59
+ policy_unavailable: 'FULI could not read what it needs to decide whether this session may be served (its session state or this call\'s task), so nothing was read, recorded or started. This is not the person stopping FULI; a later call may be served.'
60
+ });
50
61
 
51
- // Whether a call must first ask which sessions it speaks for: a tool that is
52
- // not open while FULI may be off for some session. Otherwise it runs as before.
53
- export function needsSessionFuliCheck(app, name) {
54
- return !OPEN_TOOLS.has(name) && sessionsMayBeOff(app);
62
+ // Runs an Agent's tool call (inside its request context) through the session
63
+ // layer. A tool that is not open is refused while FULI may be off for some
64
+ // session; otherwise it runs as before. A current task token an attributed
65
+ // tool carries binds the rest of the call to the token's session, so the
66
+ // capture decisions of its writes count that session as their task's, with
67
+ // its pause and stop, while another session of the client records nothing.
68
+ // A call that needs neither runs as before, synchronously.
69
+ export function runSessionGated(app, name, input, dispatch) {
70
+ const checked = !OPEN_TOOLS.has(name) && sessionsMayBeOff(app);
71
+ if (!checked && !ATTRIBUTED_TOOLS.has(name)) return dispatch();
72
+ // The client the call's process was started for decides, whatever the payload names or omits.
73
+ const sourceApplication = activeAgentHostClient() ?? input?.sourceApplication ?? 'other';
74
+ if (!checked && !sessionsMayBeWithoutCapture(app, sourceApplication)) return dispatch();
75
+ return gatedCall(app, name, input, dispatch, { checked, sourceApplication });
76
+ }
77
+
78
+ async function gatedCall(app, name, input, dispatch, { checked, sourceApplication }) {
79
+ const binding = await tokenBinding(app, input, sourceApplication);
80
+ const refusal = checked ? sessionFuliRefusal(app, input, sourceApplication, binding) : null;
81
+ if (refusal) return refusal;
82
+ return ATTRIBUTED_TOOLS.has(name) && binding.boundSessionId
83
+ ? runWithTaskBoundSession(binding.boundSessionId, dispatch) : dispatch();
55
84
  }
56
85
 
57
86
  // The refusal a tool returns instead of running, or null. The session is the
58
87
  // one the call's task token was bound to, the host session of the call or a
59
88
  // session it names (session-layer-decision.js), never one a model can choose
60
89
  // to allow it.
61
- export async function sessionFuliRefusal(app, input = {}) {
62
- // The client the call's process was started for decides, whatever the payload names or omits.
63
- const sourceApplication = activeAgentHostClient() ?? input?.sourceApplication ?? 'other';
90
+ function sessionFuliRefusal(app, input, sourceApplication, binding) {
64
91
  const decision = sessionUseDecision(app, { sourceApplication,
65
- sessionId: input?.sessionId ?? input?.sourceSessionId ?? null, boundSessionId: await boundSession(app, input, sourceApplication) });
92
+ sessionId: input?.sessionId ?? input?.sourceSessionId ?? null, ...binding });
66
93
  return decision.allowed ? null : { status: SESSION_FULI_OFF, reason: decision.reason,
67
- notice: captureNotice(decision.reason, decision.since),
68
- guidance: decision.reason === 'session_unattributed' ? UNATTRIBUTED_GUIDANCE : GUIDANCE };
94
+ notice: captureNotice(decision.reason, decision.since), guidance: REASON_GUIDANCE[decision.reason] ?? GUIDANCE };
69
95
  }
70
96
 
71
- // A token that does not resolve leaves the decision to the other identities;
72
- // the tool itself then refuses the token.
73
- async function boundSession(app, input, sourceApplication) {
97
+ // The session the call's task token is bound to or, for a token that binds it
98
+ // to none, why: it is not its session's current task, or the registry could
99
+ // not answer. That leaves the decision to the other identities; the tool
100
+ // itself then refuses the token. A value that cannot be a token says nothing.
101
+ async function tokenBinding(app, input, sourceApplication) {
74
102
  const token = input?.taskContextToken;
75
- if (typeof token !== 'string' || !token || token.length > 256 || !app.taskContextRegistry) return null;
103
+ if (typeof token !== 'string' || !token || token.length > 256 || !app.taskContextRegistry) return {};
76
104
  try {
77
- return (await app.taskContextRegistry.context(token, sourceApplication)).sessionId ?? null;
105
+ const boundSessionId = await app.taskContextRegistry.currentTaskSession(token, sourceApplication);
106
+ return boundSessionId ? { boundSessionId } : { tokenUnresolved: 'task_token_not_current' };
78
107
  } catch {
79
- return null;
108
+ return { tokenUnresolved: 'policy_unavailable' };
80
109
  }
81
110
  }
@@ -4,8 +4,7 @@ import { runWithAgentRequestContext } from './app/agent-request-context.js';
4
4
  import { ROUNDTABLE_TOOL_DEFINITIONS, ROUNDTABLE_TOOL_NAMES, callRoundtableTool } from './agent-roundtable/tools.js';
5
5
  import { ApplicationError } from './app/application-error.js';
6
6
  import { withCaptureLookups } from './graphiti/capture-decision.js';
7
- import { needsSessionFuliCheck, sessionFuliRefusal, withoutSessionAttribution, withSessionAttribution }
8
- from './agent-tools/session-fuli-gate.js';
7
+ import { runSessionGated, withoutSessionAttribution, withSessionAttribution } from './agent-tools/session-fuli-gate.js';
9
8
 
10
9
  const TOOL_DEFINITIONS = [...GRAPH_TOOL_DEFINITIONS, ...ROUNDTABLE_TOOL_DEFINITIONS].map(withSessionAttribution);
11
10
 
@@ -22,8 +21,7 @@ export function callAgentTool(app, name, input = {}, requestContext = null) {
22
21
  ? callRoundtableTool(app.roundtable, name, toolInput)
23
22
  : withCaptureLookups(() => dispatchGraphTool(app, name, toolInput));
24
23
  // A session FULI is off for gets no memory and starts no collaboration (rec#5 C3b).
25
- return runWithAgentRequestContext(requestContext, needsSessionFuliCheck(app, name)
26
- ? async () => await sessionFuliRefusal(app, input) ?? dispatch() : dispatch);
24
+ return runWithAgentRequestContext(requestContext, () => runSessionGated(app, name, input, dispatch));
27
25
  }
28
26
 
29
27
  function clone(value) {
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { randomUUID } from 'node:crypto';
3
- import { PASS_TASK_TOKEN, TASK_RULES_ON_DEMAND } from '../lifecycle-message.js';
3
+ import { PASS_TASK_TOKEN, TASK_RULES_ON_DEMAND, taskClosingInstruction } from '../lifecycle-message.js';
4
4
  import { transcriptLifecycle } from '../../conversations/transcript-lifecycle.js';
5
5
  import { transcriptCaptureScope } from '../../conversations/sync-transcript.js';
6
6
  import { captureDecision, withCaptureLookups } from '../../graphiti/capture-decision.js';
@@ -50,8 +50,9 @@ export async function claudeLifecycleOutput(event, input, invoke, { delivery, cu
50
50
  const context = await invoke('begin_task_context', {
51
51
  sessionId, projectPath: input.cwd, taskPrompt: input.prompt.slice(0, 8192), ...source, ...taskSceneInput(input.prompt)
52
52
  });
53
- return preferenceHookOutput(compactTaskContext(context), event, input, delivery, 'claude_code',
54
- 'Fuli task context. Read full context; apply effective_preferences. Follow checkpoint_guidance: checkpoint_task_knowledge only when there is something to record; the Stop hook closes the rest. ' + PASS_TASK_TOKEN + TASK_RULES_ON_DEMAND);
53
+ const entry = compactTaskContext(context);
54
+ return preferenceHookOutput(entry, event, input, delivery, 'claude_code',
55
+ 'Fuli task context. Apply effective_preferences. ' + taskClosingInstruction(entry) + PASS_TASK_TOKEN + TASK_RULES_ON_DEMAND);
55
56
  }
56
57
  const check = await invoke('verify_task_checkpoint', { sessionId, ...source });
57
58
  return stopHookOutcome(check, invoke, source);
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { randomUUID } from 'node:crypto';
3
- import { PASS_TASK_TOKEN, TASK_RULES_ON_DEMAND } from '../lifecycle-message.js';
3
+ import { PASS_TASK_TOKEN, TASK_RULES_ON_DEMAND, taskClosingInstruction } from '../lifecycle-message.js';
4
4
  import { outdatedMcpNotice, withOutdatedMcpNotice } from '../../mcp/process-registry.js';
5
5
  import { FULI_VERSION } from '../../package-metadata.js';
6
6
  import { transcriptLifecycle } from '../../conversations/transcript-lifecycle.js';
@@ -72,8 +72,9 @@ export async function codexLifecycleOutput(event, input, invoke, { delivery, cur
72
72
  const context = await invoke('begin_task_context', { sessionId: input.session_id,
73
73
  turnId: input.turn_id ?? null, projectPath: input.cwd, taskPrompt: input.prompt.slice(0, 8192),
74
74
  sourceApplication: 'codex', sourceSessionId: input.session_id, ...taskSceneInput(input.prompt) });
75
- const output = await preferenceHookOutput(compactTaskContext(context), event, input, delivery, 'codex',
76
- 'Fuli task context. Apply effective_preferences. Follow checkpoint_guidance: checkpoint with taskContextToken only when there is something to record; the Stop hook closes the rest. ' + PASS_TASK_TOKEN + TASK_RULES_ON_DEMAND);
75
+ const entry = compactTaskContext(context);
76
+ const output = await preferenceHookOutput(entry, event, input, delivery, 'codex',
77
+ 'Fuli task context. Apply effective_preferences. ' + taskClosingInstruction(entry) + PASS_TASK_TOKEN + TASK_RULES_ON_DEMAND);
77
78
  return review ? withCodexReviewGuidance(output) : output;
78
79
  }
79
80
 
@@ -5,6 +5,24 @@
5
5
  export const PASS_TASK_TOKEN = 'Pass taskContextToken to every FULI call. ';
6
6
  export const TASK_RULES_ON_DEMAND = 'Shared rules are referenced by version. Do not read fuli://rules/task-entry for an ordinary task; read one referenced section only when you must act on it (workers, memory merge, conflicts).';
7
7
 
8
+ // How a hook-delivered task ends, in the entry's own label (rec#47 F1). The
9
+ // entry only references the checkpoint and receipt rules, and a host may keep
10
+ // just a preview of a long entry, so the label carries the token and receipt.
11
+ // The Stop hook closes a task whose entry has checkpoint_guidance
12
+ // (stop-auto-close.js); a required checkpoint is left to the model.
13
+ export function taskClosingInstruction(entry) {
14
+ const token = entry?.taskContextToken;
15
+ if (typeof token !== 'string') return '';
16
+ const call = `checkpoint_task_knowledge with taskContextToken ${JSON.stringify(token)}`;
17
+ const checkpoint = entry.checkpoint_required === true ? `Before your final reply, call ${call}. `
18
+ : entry.checkpoint_guidance ? `The Stop hook closes this task. Call ${call} only when something is worth recording `
19
+ + '(knowledge, experience, memory changes, collaborators, a meaningful workLog). ' : '';
20
+ const receipt = entry.agent_receipt?.required === true && typeof entry.agent_receipt.markdown === 'string'
21
+ ? `End your final reply with this agent_receipt markdown, unchanged and once: ${JSON.stringify(entry.agent_receipt.markdown)} `
22
+ + '(a receipt returned by checkpoint_task_knowledge replaces it). ' : '';
23
+ return checkpoint + receipt;
24
+ }
25
+
8
26
  const DEFAULT_MAX_BYTES = 8_000;
9
27
  const TRUNCATION_SUFFIX = '… [truncated]';
10
28
 
@@ -1,4 +1,5 @@
1
1
  import { receiptConsoleUrl, receiptSummary, receiptText, sessionRecordsUrl } from './identity-receipt.js';
2
+ import { providerReaderFields } from '../graphiti/knowledge-reader.js';
2
3
 
3
4
  // The per-turn receipt (rec#20): after a turn's checkpoint saved knowledge, the
4
5
  // reply tail lists every item that turn actually created or replaced, read back
@@ -34,10 +35,12 @@ function turnReceiptListUrl(application, episodeIds) {
34
35
  // The receipt of saved capture results: null when nothing substantive changed.
35
36
  // memory is the Agent working-memory write this checkpoint made, if any.
36
37
  // session: { sourceApplication, sessionId } of the turn, for the session link.
38
+ // reader: the turn's FLA (knowledge-reader.js), or null for a plain session.
37
39
  export async function readTurnReceipt(application, captureResults, { memory = null, agentName = null,
38
- heading = '本轮沉淀', session = null } = {}) {
40
+ heading = '本轮沉淀', session = null, reader = null } = {}) {
39
41
  const episodeIds = savedEpisodeIds(captureResults);
40
- const { entries } = episodeIds.length ? await readEpisodeReceipts(application, episodeIds) : { entries: [] };
42
+ const { entries } = episodeIds.length ? await readEpisodeReceipts(application, episodeIds, { reader })
43
+ : { entries: [] };
41
44
  return renderTurnReceipt(application, entries, { episodeIds, memory, agentName, heading, session });
42
45
  }
43
46
 
@@ -52,19 +55,23 @@ export function renderTurnReceipt(application, entries, { episodeIds, memory = n
52
55
 
53
56
  // What the episodes created or replaced, read in the Provider's batches and
54
57
  // merged, so a late receipt of several turns and its full list read the same.
55
- export async function readEpisodeReceipts(application, episodeIds) {
58
+ // An Agent's receipt reads as its reader and leaves out every other FLA's
59
+ // items; the console's full list passes read, its human-review port.
60
+ export async function readEpisodeReceipts(application, episodeIds, {
61
+ reader = null, read = body => application.personal.readTurnReceipt({ ...body, ...providerReaderFields(reader) })
62
+ } = {}) {
56
63
  const entries = new Map();
57
64
  let unchanged = 0;
58
65
  const deletions = new Set();
59
66
  for (let start = 0; start < episodeIds.length; start += EPISODES_PER_READ) {
60
- const read = await application.personal.readTurnReceipt({ personal_space_id: application.config.personal.spaceId,
67
+ const batch = await read({ personal_space_id: application.config.personal.spaceId,
61
68
  episode_ids: episodeIds.slice(start, start + EPISODES_PER_READ) });
62
- if (!Array.isArray(read?.entries)) throw new TypeError('Provider did not return the turn receipt');
63
- for (const entry of read.entries) entries.set(`${entry.item_kind}:${entry.item_id}`, entry);
64
- unchanged += read.unchanged_count ?? 0;
69
+ if (!Array.isArray(batch?.entries)) throw new TypeError('Provider did not return the turn receipt');
70
+ for (const entry of batch.entries) entries.set(`${entry.item_kind}:${entry.item_id}`, entry);
71
+ unchanged += batch.unchanged_count ?? 0;
65
72
  // What a person hard-deleted since (rec#5 C9), each delete once even when
66
73
  // its sources span two reads.
67
- for (const id of read.deletion_ids ?? []) deletions.add(id);
74
+ for (const id of batch.deletion_ids ?? []) deletions.add(id);
68
75
  }
69
76
  return { entries: [...entries.values()], unchanged_count: unchanged, deleted_count: deletions.size };
70
77
  }
@@ -37,6 +37,24 @@ export function agentHostRequestContext(value, hostSessionId, sourceApplication
37
37
  ...(sourceApplication ? { [HOST_CLIENT]: sourceApplication } : {}) };
38
38
  }
39
39
 
40
+ // Runs the rest of an Agent call for the session its task token is bound to.
41
+ // Only the session gate calls this, with the session the task registry
42
+ // resolved for a current token (session-fuli-gate.js); a payload field or a raw
43
+ // token never reaches it. Every session decision of the call then counts that
44
+ // session as the call's task session.
45
+ export function runWithTaskBoundSession(sessionId, operation) {
46
+ const store = requestContext.getStore();
47
+ if (!store || typeof sessionId !== 'string' || !sessionId) {
48
+ throw new TypeError('A task-bound session needs an Agent request and a resolved session');
49
+ }
50
+ return requestContext.run({ ...store, taskBoundSession: sessionId }, operation);
51
+ }
52
+
53
+ // The session the call's current task token was resolved to, or null.
54
+ export function activeTaskBoundSession() {
55
+ return requestContext.getStore()?.taskBoundSession ?? null;
56
+ }
57
+
40
58
  // The host session of the Agent call being served: a session ID, null when the
41
59
  // client named none, undefined outside an Agent's own call (hooks, console).
42
60
  export function activeAgentHostSession() {
@@ -19,7 +19,10 @@ const REASON_NOTICES = Object.freeze({
19
19
  session_start_unsaved: 'FULI 未能保存本会话开始时的设置,本会话保持停用,输入 /fuli start 可启用',
20
20
  // The call carries no task token and its client cannot say which session it
21
21
  // is, while one of that client's sessions has FULI off (session-layer-decision.js).
22
- session_unattributed: 'FULI 无法确认这次调用来自哪个会话,而本客户端有会话已停用 FULI,所以没有提供'
22
+ session_unattributed: 'FULI 无法确认这次调用来自哪个会话,而本客户端有会话已停用 FULI,所以没有提供',
23
+ // The call's task token is not its session's current task (each new prompt
24
+ // begins a new one), under the same condition (session-fuli-gate.js).
25
+ task_token_not_current: '这次调用带的任务 token 已不是会话当前的任务(每次新的提问都会换新 token),而本客户端有会话已停用 FULI,所以没有提供'
23
26
  });
24
27
  // The global and client switches, and any reason without wording of its own.
25
28
  const RECORDING_OFF = '自动记录已关闭';