Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(projects): inherit agent assignments for incoming tasks (#7356)

Eric Hayesa3da27a5ab6d
diff --git a/Cargo.lock b/Cargo.lock
index 3a9484b13a..259668457c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -452,6 +452,7 @@ dependencies = [
"messages",
"notification",
"pipedream_mcp",
+ "properties",
"rdkafka",
"redis",
"rmcp",
@@ -666,6 +667,7 @@ dependencies = [
"document_storage_service_client",
"document_sub_type",
"entity_access",
+ "initiative",
"lexical_client",
"macro_event_broker",
"macro_event_topics",
@@ -717,6 +719,7 @@ dependencies = [
"macro_event_broker",
"macro_service_urls",
"messages",
+ "properties",
"rdkafka",
"roles_and_permissions",
"rootcause",
diff --git a/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx b/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx
index 1b2971a3ca..50295bff3c 100644
--- a/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx
+++ b/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx
@@ -1,3 +1,4 @@
+import type { EntityType } from '@service-properties/generated/schemas/entityType';
import {
cleanup,
fireEvent,
@@ -107,7 +108,10 @@ const property: EntityProperty = {
value: [{ entity_id: userId, entity_type: 'USER' }],
};
-function setup(existingTask: boolean, value = property) {
+function setup(
+ selfFilter?: { entityType: EntityType; blockId?: string },
+ value = property
+) {
const onSave = vi.fn(async () => undefined);
const [editorOpen, setEditorOpen] = createSignal(true);
const context: PropertyRootContextValue = {
@@ -120,11 +124,7 @@ function setup(existingTask: boolean, value = property) {
};
render(() => (
<PropertyRootContext.Provider value={context}>
- <EntityEditor
- selfFilter={
- existingTask ? { entityType: 'TASK', blockId: 'task-id' } : undefined
- }
- />
+ <EntityEditor selfFilter={selfFilter} />
</PropertyRootContext.Provider>
));
return onSave;
@@ -132,13 +132,29 @@ function setup(existingTask: boolean, value = property) {
afterEach(cleanup);
-describe('assigning an agent through task properties', () => {
- it.each([false, true])(
- 'saves the bot principal alongside the human assignee (existing task: %s)',
- async (existingTask) => {
- const onSave = setup(existingTask);
+describe('assigning an agent through task and project properties', () => {
+ it.each([
+ { name: 'new task', selfFilter: undefined },
+ {
+ name: 'existing task',
+ selfFilter: { entityType: 'TASK' as const, blockId: 'task-id' },
+ },
+ { name: 'new project', selfFilter: { entityType: 'INITIATIVE' as const } },
+ {
+ name: 'existing project',
+ selfFilter: { entityType: 'INITIATIVE' as const, blockId: 'project-id' },
+ },
+ ])(
+ 'saves the bot principal alongside the human assignee in a $name',
+ async ({ selfFilter }) => {
+ const onSave = setup(selfFilter);
expect(screen.getByText('Alice')).toBeTruthy();
expect(screen.getByText('Agent')).toBeTruthy();
+ expect(
+ screen.queryByText(
+ 'Agents assigned to this project automatically take on tasks created in or moved into it. Use a shared team agent for tasks added by teammates.'
+ ) !== null
+ ).toBe(selfFilter?.entityType === 'INITIATIVE');
fireEvent.input(screen.getByPlaceholderText('Add assignees...'), {
target: { value: 'research' },
});
@@ -158,32 +174,43 @@ describe('assigning an agent through task properties', () => {
}
);
- it('does not resave an unchanged assignment and can remove the agent', async () => {
- const assigned: EntityProperty = {
- ...property,
- value: [{ entity_id: agentId, entity_type: 'USER' }],
- };
- const unchanged = setup(true, assigned);
- fireEvent.click(screen.getByText('Dismiss'));
- expect(unchanged).not.toHaveBeenCalled();
- cleanup();
- const onSave = setup(true, assigned);
- fireEvent.click(screen.getByText('Research assistant'));
- fireEvent.click(screen.getByText('Dismiss'));
- await waitFor(() =>
- expect(onSave).toHaveBeenCalledExactlyOnceWith(assigned, {
- valueType: 'ENTITY',
- refs: null,
- })
- );
- });
+ it.each(['TASK', 'INITIATIVE'] as const)(
+ 'does not resave an unchanged assignment and can remove the agent from %s',
+ async (entityType) => {
+ const assigned: EntityProperty = {
+ ...property,
+ value: [{ entity_id: agentId, entity_type: 'USER' }],
+ };
+ const unchanged = setup({ entityType, blockId: 'entity-id' }, assigned);
+ fireEvent.click(screen.getByText('Dismiss'));
+ expect(unchanged).not.toHaveBeenCalled();
+ cleanup();
+ const onSave = setup({ entityType, blockId: 'entity-id' }, assigned);
+ fireEvent.click(screen.getByText('Research assistant'));
+ fireEvent.click(screen.getByText('Dismiss'));
+ await waitFor(() =>
+ expect(onSave).toHaveBeenCalledExactlyOnceWith(assigned, {
+ valueType: 'ENTITY',
+ refs: null,
+ })
+ );
+ }
+ );
it('keeps agents out of unrelated people properties', () => {
- setup(false, {
- ...property,
- propertyDefinitionId: 'custom-people-property',
- });
+ setup(
+ { entityType: 'INITIATIVE', blockId: 'project-id' },
+ {
+ ...property,
+ propertyDefinitionId: 'custom-people-property',
+ }
+ );
expect(screen.getByText('Alice')).toBeTruthy();
expect(screen.queryByText('Research assistant')).toBeNull();
+ expect(
+ screen.queryByText(
+ 'Agents assigned to this project automatically take on tasks created in or moved into it. Use a shared team agent for tasks added by teammates.'
+ )
+ ).toBeNull();
});
});
diff --git a/apps/web/src/features/property/editors/popover/EntityEditor.tsx b/apps/web/src/features/property/editors/popover/EntityEditor.tsx
index a3687fea22..0c26f4e241 100644
--- a/apps/web/src/features/property/editors/popover/EntityEditor.tsx
+++ b/apps/web/src/features/property/editors/popover/EntityEditor.tsx
@@ -119,6 +119,18 @@ function EntityEditorBody(props: EntityEditorProps) {
onClose={closeAndSave}
/>
</Suspense>
+ <Show
+ when={
+ props.selfFilter?.entityType === 'INITIATIVE' &&
+ property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.ASSIGNEES
+ }
+ >
+ <p class="border-t border-edge-muted px-3 py-2 text-xs text-ink-muted">
+ Agents assigned to this project automatically take on tasks created in
+ or moved into it. Use a shared team agent for tasks added by
+ teammates.
+ </p>
+ </Show>
</EditorPopover>
);
}
diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.toml
index dd4a6318b4..d3f1940fd6 100644
--- a/crates/agent_trigger/Cargo.toml
+++ b/crates/agent_trigger/Cargo.toml
@@ -38,6 +38,7 @@ channel_sender = { path = "../channel_sender" }
macro_uuid = { path = "../macro_uuid" }
messages = { path = "../messages", features = ["broker", "ports"] }
properties = { path = "../properties", default-features = false }
+initiative = { path = "../initiative", default-features = false, features = ["ports"] }
models_properties = { path = "../models_properties" }
system_properties = { path = "../system_properties" }
# Domain vocabulary: channel-parent trigger events keep the channel-only post
diff --git a/crates/agent_trigger/src/domain/mod.rs b/crates/agent_trigger/src/domain/mod.rs
index 618ead0cea..4781a6edaf 100644
--- a/crates/agent_trigger/src/domain/mod.rs
+++ b/crates/agent_trigger/src/domain/mod.rs
@@ -1,5 +1,6 @@
pub mod broker_events;
pub mod processing;
+pub mod project_assignment;
pub mod service;
pub mod sources;
pub mod task_assignment;
diff --git a/crates/agent_trigger/src/domain/project_assignment.rs b/crates/agent_trigger/src/domain/project_assignment.rs
new file mode 100644
index 0000000000..c7203e3bf8
--- /dev/null
+++ b/crates/agent_trigger/src/domain/project_assignment.rs
@@ -0,0 +1,246 @@
+//! Inherit project agents when a task enters a project.
+
+use std::collections::HashMap;
+
+use entity_access::domain::{
+ models::{AccessError, BotAccessScope, EntityAccessReceipt, EntityType, RequiredPermission},
+ ports::EntityAccessService,
+};
+use initiative::domain::{
+ events::{InitiativeEventActor, InitiativeTasksChanged},
+ models::{InitiativeError, InitiativeId},
+ ports::InitiativeRepo,
+};
+use properties::{EditReceipt, PropertiesErr, PropertiesService, ViewReceipt};
+
+#[cfg(test)]
+mod test;
+
+/// Failure to read or apply a project assignment; the consumer retries the event.
+#[derive(Debug, thiserror::Error)]
+pub enum ProjectAssignmentError {
+ /// Current project membership could not be read.
+ #[error(transparent)]
+ Initiative(#[from] InitiativeError),
+ /// Current access could not be checked.
+ #[error(transparent)]
+ Access(#[from] AccessError),
+ /// Assignees could not be inherited.
+ #[error(transparent)]
+ Properties(#[from] PropertiesErr),
+}
+
+/// The current membership facts needed to discard superseded queued moves.
+#[cfg_attr(test, mockall::automock)]
+pub trait ProjectMemberships: Send + Sync {
+ /// Read all candidate tasks in one batch.
+ fn memberships(
+ &self,
+ tasks: Vec<String>,
+ ) -> impl Future<Output = Result<HashMap<String, InitiativeId>, InitiativeError>> + Send;
+}
+
+impl<R: InitiativeRepo> ProjectMemberships for R {
+ async fn memberships(
+ &self,
+ tasks: Vec<String>,
+ ) -> Result<HashMap<String, InitiativeId>, InitiativeError> {
+ self.task_memberships(tasks).await.map_err(Into::into)
+ }
+}
+
+/// Current capabilities for the user responsible for the membership change.
+#[cfg_attr(test, mockall::automock)]
+pub trait ProjectAssignmentAccess: Send + Sync {
+ /// Missing access discards the assignment; infrastructure failures retry it.
+ fn receipts(
+ &self,
+ actor: &InitiativeEventActor,
+ project: InitiativeId,
+ task: &str,
+ ) -> impl Future<Output = Result<Option<(ViewReceipt, EditReceipt)>, AccessError>> + Send;
+}
+
+impl<A: EntityAccessService> ProjectAssignmentAccess for A {
+ async fn receipts(
+ &self,
+ actor: &InitiativeEventActor,
+ project: InitiativeId,
+ task: &str,
+ ) -> Result<Option<(ViewReceipt, EditReceipt)>, AccessError> {
+ let Some(project) = current_access(
+ attributed_receipt(self, actor, &project.to_string(), EntityType::Initiative).await,
+ )?
+ else {
+ return Ok(None);
+ };
+ let Some(task) =
+ current_access(attributed_receipt(self, actor, task, EntityType::Document).await)?
+ else {
+ return Ok(None);
+ };
+ Ok(Some((project, task)))
+ }
+}
+
+async fn attributed_receipt<A: EntityAccessService, T: RequiredPermission>(
+ access: &A,
+ attribution: &InitiativeEventActor,
+ entity_id: &str,
+ entity_type: EntityType,
+) -> Result<EntityAccessReceipt<T>, AccessError> {
+ if let Some(user) = attribution.actor.as_user() {
+ return access
+ .generate_entity_access_receipt(user, None, entity_id, entity_type)
+ .await;
+ }
+ let bot = attribution
+ .actor
+ .as_bot()
+ .ok_or(AccessError::Unauthorized)?;
+ let user = attribution
+ .on_behalf_of
+ .clone()
+ .ok_or(AccessError::Unauthorized)?;
+ access
+ .generate_bot_entity_access_receipt(
+ bot.bot_id(),
+ BotAccessScope::user(user),
+ entity_id,
+ entity_type,
+ )
+ .await
+}
+
+fn current_access<T>(result: Result<T, AccessError>) -> Result<Option<T>, AccessError> {
+ match result {
+ Ok(receipt) => Ok(Some(receipt)),
+ Err(
+ AccessError::Unauthorized
+ | AccessError::UnauthorizedWithMessage(_)
+ | AccessError::NotFound(_),
+ ) => Ok(None),
+ Err(error) => Err(error),
+ }
+}
+
+/// The property domain's atomic merge of project agents into task assignees.
+#[cfg_attr(test, mockall::automock)]
+pub trait ProjectAgentInheritance: Send + Sync {
+ /// Preserve existing assignees and publish the committed assignment delta.
+ fn inherit(
+ &self,
+ project: &ViewReceipt,
+ task: &EditReceipt,
+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;
+}
+
+impl<P: PropertiesService> ProjectAgentInheritance for P {
+ async fn inherit(
+ &self,
+ project: &ViewReceipt,
+ task: &EditReceipt,
+ ) -> Result<(), PropertiesErr> {
+ self.inherit_project_agent_assignees(project, task).await
+ }
+}
+
+/// Applies project defaults to committed additions and moves, never existing tasks.
+pub struct ProjectAssignmentService<P, I, A> {
+ properties: P,
+ initiatives: I,
+ access: A,
+}
+
+impl<P: ProjectAgentInheritance, I: ProjectMemberships, A: ProjectAssignmentAccess>
+ ProjectAssignmentService<P, I, A>
+{
+ /// Compose the owning property, initiative, and access capabilities.
+ pub fn new(properties: P, initiatives: I, access: A) -> Self {
+ Self {
+ properties,
+ initiatives,
+ access,
+ }
+ }
+
+ /// Recheck queued membership changes before inheriting the destination's agents.
+ #[tracing::instrument(err, skip_all)]
+ pub async fn process(
+ &self,
+ event: &InitiativeTasksChanged,
+ ) -> Result<(), ProjectAssignmentError> {
+ let Some(attribution) = &event.attribution else {
+ return Ok(());
+ };
+ let Some(_) = attribution
+ .actor
+ .as_user()
+ .or(attribution.on_behalf_of.as_ref())
+ else {
+ return Ok(());
+ };
+ let additions: Vec<_> = event
+ .changes
+ .iter()
+ .filter(|change| change.to.is_some() && change.to != change.from)
+ .collect();
+ if additions.is_empty() {
+ return Ok(());
+ }
+ let memberships = self
+ .initiatives
+ .memberships(
+ additions
+ .iter()
+ .map(|change| change.task_id.clone())
+ .collect(),
+ )
+ .await?;
+ for change in additions {
+ let Some(project_id) = change
+ .to
+ .filter(|id| memberships.get(&change.task_id) == Some(id))
+ else {
+ continue;
+ };
+ let Some((project, task)) = self
+ .access
+ .receipts(attribution, project_id, &change.task_id)
+ .await?
+ else {
+ continue;
+ };
+ match self.properties.inherit(&project, &task).await {
+ Ok(()) => {}
+ Err(
+ error
+ @ (PropertiesErr::Repo(_) | PropertiesErr::PermissionServiceNotConfigured),
+ ) => {
+ return Err(error.into());
+ }
+ Err(
+ error @ (PropertiesErr::Validation(_)
+ | PropertiesErr::PermissionDenied
+ | PropertiesErr::NotFound
+ | PropertiesErr::OptionNotFound
+ | PropertiesErr::EntityPropertyNotFound
+ | PropertiesErr::RequiredProperty
+ | PropertiesErr::DuplicateOptionValue
+ | PropertiesErr::ConflictingTeamLabel(_)
+ | PropertiesErr::SystemPropertyNotModifiable
+ | PropertiesErr::TeamMembershipRequired
+ | PropertiesErr::ManagedDefinition),
+ ) => {
+ tracing::warn!(
+ error = ?error,
+ task_id = %change.task_id,
+ project_id = %project_id,
+ "skipping invalid project agent assignment"
+ );
+ }
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/crates/agent_trigger/src/domain/project_assignment/test.rs b/crates/agent_trigger/src/domain/project_assignment/test.rs
new file mode 100644
index 0000000000..84a7df414a
--- /dev/null
+++ b/crates/agent_trigger/src/domain/project_assignment/test.rs
@@ -0,0 +1,361 @@
+use super::*;
+use channel_sender::ChannelSender;
+use chrono::Utc;
+use entity_access::domain::models::{
+ AccessLevel, Entity, EntityAccessReceipt, EntityPermission, RequiredPermission,
+};
+use initiative::domain::events::{InitiativeEventActor, TaskMembershipChange};
+use macro_user_id::user_id::MacroUserIdStr;
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn event(changes: Vec<TaskMembershipChange>) -> InitiativeTasksChanged {
+ InitiativeTasksChanged {
+ attribution: Some(InitiativeEventActor {
+ actor: ChannelSender::new_from_user(user()),
+ on_behalf_of: None,
+ }),
+ changes,
+ occurred_at: Utc::now(),
+ }
+}
+
+fn receipt<T: RequiredPermission>(id: String, entity_type: EntityType) -> EntityAccessReceipt<T> {
+ EntityAccessReceipt::try_new_authenticated_user(
+ user(),
+ Entity {
+ entity_id: id,
+ entity_type,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ )
+ .unwrap()
+}
+
+fn allowed_receipts(
+ _: &InitiativeEventActor,
+ project: InitiativeId,
+ task: &str,
+) -> std::pin::Pin<
+ Box<dyn Future<Output = Result<Option<(ViewReceipt, EditReceipt)>, AccessError>> + Send>,
+> {
+ let receipts = (
+ receipt(project.to_string(), EntityType::Initiative),
+ receipt(task.to_owned(), EntityType::Document),
+ );
+ Box::pin(async move { Ok(Some(receipts)) })
+}
+
+#[tokio::test]
+async fn new_tasks_and_moves_inherit_independently_with_their_own_receipts() {
+ let project = InitiativeId::generate();
+ let previous = InitiativeId::generate();
+ let event = event(vec![
+ TaskMembershipChange {
+ task_id: "new-task".into(),
+ from: None,
+ to: Some(project),
+ },
+ TaskMembershipChange {
+ task_id: "moved-task".into(),
+ from: Some(previous),
+ to: Some(project),
+ },
+ ]);
+ let mut memberships = MockProjectMemberships::new();
+ memberships
+ .expect_memberships()
+ .once()
+ .withf(|ids| ids == &["new-task", "moved-task"])
+ .return_once(move |_| {
+ Box::pin(async move {
+ Ok(HashMap::from([
+ ("new-task".into(), project),
+ ("moved-task".into(), project),
+ ]))
+ })
+ });
+ let mut access = MockProjectAssignmentAccess::new();
+ access
+ .expect_receipts()
+ .times(2)
+ .withf(move |actor, id, _| actor.actor.as_user() == Some(&user()) && *id == project)
+ .returning(allowed_receipts);
+ let mut properties = MockProjectAgentInheritance::new();
+ properties
+ .expect_inherit()
+ .once()
+ .withf(move |source, target| {
+ source.entity().entity_id == project.to_string()
+ && target.entity().entity_id == "new-task"
+ })
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ properties
+ .expect_inherit()
+ .once()
+ .withf(move |source, target| {
+ source.entity().entity_id == project.to_string()
+ && target.entity().entity_id == "moved-task"
+ })
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ ProjectAssignmentService::new(properties, memberships, access)
+ .process(&event)
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn removals_unchanged_membership_and_unattributed_events_do_nothing() {
+ let project = InitiativeId::generate();
+ let service = ProjectAssignmentService::new(
+ MockProjectAgentInheritance::new(),
+ MockProjectMemberships::new(),
+ MockProjectAssignmentAccess::new(),
+ );
+ let mut event = event(vec![
+ TaskMembershipChange {
+ task_id: "removed".into(),
+ from: Some(project),
+ to: None,
+ },
+ TaskMembershipChange {
+ task_id: "unchanged".into(),
+ from: Some(project),
+ to: Some(project),
+ },
+ ]);
+ service.process(&event).await.unwrap();
+ event.changes[0].to = Some(InitiativeId::generate());
+ event.attribution = None;
+ service.process(&event).await.unwrap();
+ event.attribution = Some(InitiativeEventActor {
+ actor: ChannelSender::new_from_bot(bot_id::BotId::TEST_A),
+ on_behalf_of: None,
+ });
+ service.process(&event).await.unwrap();
+}
+
+#[tokio::test]
+async fn superseded_moves_and_tasks_without_membership_are_skipped() {
+ let project = InitiativeId::generate();
+ let event = event(vec![
+ TaskMembershipChange {
+ task_id: "moved-again".into(),
+ from: None,
+ to: Some(project),
+ },
+ TaskMembershipChange {
+ task_id: "unassigned".into(),
+ from: None,
+ to: Some(project),
+ },
+ ]);
+ let mut memberships = MockProjectMemberships::new();
+ memberships.expect_memberships().once().return_once(|_| {
+ Box::pin(async {
+ Ok(HashMap::from([(
+ "moved-again".into(),
+ InitiativeId::generate(),
+ )]))
+ })
+ });
+ ProjectAssignmentService::new(
+ MockProjectAgentInheritance::new(),
+ memberships,
+ MockProjectAssignmentAccess::new(),
+ )
+ .process(&event)
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn revoked_access_skips_only_the_affected_task() {
+ let project = InitiativeId::generate();
+ let event = event(vec![
+ TaskMembershipChange {
+ task_id: "revoked".into(),
+ from: None,
+ to: Some(project),
+ },
+ TaskMembershipChange {
+ task_id: "allowed".into(),
+ from: None,
+ to: Some(project),
+ },
+ ]);
+ let mut memberships = MockProjectMemberships::new();
+ memberships
+ .expect_memberships()
+ .once()
+ .return_once(move |_| {
+ Box::pin(async move {
+ Ok(HashMap::from([
+ ("revoked".into(), project),
+ ("allowed".into(), project),
+ ]))
+ })
+ });
+ let mut access = MockProjectAssignmentAccess::new();
+ access
+ .expect_receipts()
+ .once()
+ .withf(|_, _, task| task == "revoked")
+ .returning(|_, _, _| Box::pin(async { Ok(None) }));
+ access
+ .expect_receipts()
+ .once()
+ .withf(|_, _, task| task == "allowed")
+ .returning(allowed_receipts);
+ let mut properties = MockProjectAgentInheritance::new();
+ properties
+ .expect_inherit()
+ .once()
+ .withf(|_, task| task.entity().entity_id == "allowed")
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ ProjectAssignmentService::new(properties, memberships, access)
+ .process(&event)
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn delegated_changes_recheck_the_delegating_users_access() {
+ let project = InitiativeId::generate();
+ let mut event = event(vec![TaskMembershipChange {
+ task_id: "task".into(),
+ from: None,
+ to: Some(project),
+ }]);
+ event.attribution = Some(InitiativeEventActor {
+ actor: ChannelSender::new_from_bot(bot_id::BotId::TEST_A),
+ on_behalf_of: Some(user()),
+ });
+ let mut memberships = MockProjectMemberships::new();
+ memberships
+ .expect_memberships()
+ .once()
+ .return_once(move |_| {
+ Box::pin(async move { Ok(HashMap::from([("task".into(), project)])) })
+ });
+ let mut access = MockProjectAssignmentAccess::new();
+ access
+ .expect_receipts()
+ .once()
+ .withf(|actor, _, _| actor.on_behalf_of.as_ref() == Some(&user()))
+ .returning(allowed_receipts);
+ let mut properties = MockProjectAgentInheritance::new();
+ properties
+ .expect_inherit()
+ .once()
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ ProjectAssignmentService::new(properties, memberships, access)
+ .process(&event)
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn inheritance_failure_is_propagated_for_retry() {
+ let project = InitiativeId::generate();
+ let event = event(vec![TaskMembershipChange {
+ task_id: "task".into(),
+ from: None,
+ to: Some(project),
+ }]);
+ let mut memberships = MockProjectMemberships::new();
+ memberships
+ .expect_memberships()
+ .once()
+ .return_once(move |_| {
+ Box::pin(async move { Ok(HashMap::from([("task".into(), project)])) })
+ });
+ let mut access = MockProjectAssignmentAccess::new();
+ access.expect_receipts().once().returning(allowed_receipts);
+ let mut properties = MockProjectAgentInheritance::new();
+ properties.expect_inherit().once().returning(|_, _| {
+ Box::pin(async { Err(PropertiesErr::Repo(anyhow::anyhow!("database unavailable"))) })
+ });
+ assert!(matches!(
+ ProjectAssignmentService::new(properties, memberships, access)
+ .process(&event)
+ .await,
+ Err(ProjectAssignmentError::Properties(_))
+ ));
+}
+
+#[tokio::test]
+async fn invalid_assignment_does_not_block_later_tasks() {
+ for failure in [
+ PropertiesErr::Validation("invalid stored assignees".into()),
+ PropertiesErr::PermissionDenied,
+ PropertiesErr::NotFound,
+ ] {
+ let project = InitiativeId::generate();
+ let event = event(vec![
+ TaskMembershipChange {
+ task_id: "invalid".into(),
+ from: None,
+ to: Some(project),
+ },
+ TaskMembershipChange {
+ task_id: "valid".into(),
+ from: None,
+ to: Some(project),
+ },
+ ]);
+ let mut memberships = MockProjectMemberships::new();
+ memberships
+ .expect_memberships()
+ .once()
+ .return_once(move |_| {
+ Box::pin(async move {
+ Ok(HashMap::from([
+ ("invalid".into(), project),
+ ("valid".into(), project),
+ ]))
+ })
+ });
+ let mut access = MockProjectAssignmentAccess::new();
+ access
+ .expect_receipts()
+ .times(2)
+ .returning(allowed_receipts);
+ let mut properties = MockProjectAgentInheritance::new();
+ properties
+ .expect_inherit()
+ .once()
+ .withf(|_, task| task.entity().entity_id == "invalid")
+ .return_once(move |_, _| Box::pin(async move { Err(failure) }));
+ properties
+ .expect_inherit()
+ .once()
+ .withf(|_, task| task.entity().entity_id == "valid")
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+
+ ProjectAssignmentService::new(properties, memberships, access)
+ .process(&event)
+ .await
+ .unwrap();
+ }
+}
+
+#[test]
+fn denied_access_is_skipped_but_broken_access_checks_are_retried() {
+ assert!(
+ current_access::<()>(Err(AccessError::Unauthorized))
+ .unwrap()
+ .is_none()
+ );
+ assert!(
+ current_access::<()>(Err(AccessError::NotFound("unassigned")))
+ .unwrap()
+ .is_none()
+ );
+ assert!(current_access::<()>(Err(AccessError::internal("failed"))).is_err());
+ assert_eq!(current_access(Ok(42)).unwrap(), Some(42));
+}
diff --git a/crates/agent_trigger/src/domain/sources.rs b/crates/agent_trigger/src/domain/sources.rs
index 63a2da2991..025170f8f1 100644
--- a/crates/agent_trigger/src/domain/sources.rs
+++ b/crates/agent_trigger/src/domain/sources.rs
@@ -3,19 +3,23 @@
//!
//! `message.posted` on `macro.messages` is the source of record: it carries the
//! persisted parent, so a mention in a document discussion routes like one in a
-//! channel. The consumer also reads `macro.properties` for task assignments.
+//! channel. The consumer also reads properties and project membership changes
+//! for task assignments.
#[cfg(test)]
mod test;
use super::processing::TriggerInput;
use super::task_assignment::TaskAssignment;
+use initiative::domain::events::{
+ InitiativeMacroEvent, InitiativeTasksChanged, InitiativeTopicEvent,
+};
use macro_event_broker::{MacroEvent as _, MacroEventCollection};
use macro_uuid::Uuid;
use messages::outbound::broker::{MessageMacroEvent, MessageTopicEvent};
use properties::domain::events::{PropertyMacroEvent, PropertyTopicEvent};
-macro_event_broker::declare_topics!(MessageTriggerEvents: MessageMacroEvent, PropertyMacroEvent);
+macro_event_broker::declare_topics!(MessageTriggerEvents: MessageMacroEvent, PropertyMacroEvent, InitiativeMacroEvent);
/// A decoded broker record from the trigger source.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -29,6 +33,8 @@ pub struct DecodedTrigger {
pub posted: Option<TriggerInput>,
/// Newly assigned agents, from a task assignment property update.
pub assignment: Option<TaskAssignment>,
+ /// Tasks entering or leaving a project; additions inherit project agents.
+ pub project_tasks: Option<InitiativeTasksChanged>,
}
/// A topic collection whose records may carry a committed post.
@@ -42,6 +48,7 @@ impl TriggerEvents for MessageTriggerEvents {
let event = match self {
Self::MessageMacroEvent(event) => event,
Self::PropertyMacroEvent(event) => return property_trigger(event),
+ Self::InitiativeMacroEvent(event) => return initiative_trigger(event),
};
let envelope = event.event();
let (event_type, posted) = match &envelope.event {
@@ -63,6 +70,7 @@ impl TriggerEvents for MessageTriggerEvents {
event_type,
posted,
assignment: None,
+ project_tasks: None,
}
}
}
@@ -87,5 +95,25 @@ fn property_trigger(event: PropertyMacroEvent) -> DecodedTrigger {
event_type,
posted: None,
assignment,
+ project_tasks: None,
+ }
+}
+
+fn initiative_trigger(event: InitiativeMacroEvent) -> DecodedTrigger {
+ let envelope = event.event();
+ let (event_type, project_tasks) = match &envelope.event {
+ InitiativeTopicEvent::Created(_) => ("initiative.created", None),
+ InitiativeTopicEvent::Updated(_) => ("initiative.updated", None),
+ InitiativeTopicEvent::TasksChanged(changes) => {
+ ("initiative.tasks_changed", Some(changes.clone()))
+ }
+ InitiativeTopicEvent::Purged { .. } => ("initiative.purged", None),
+ };
+ DecodedTrigger {
+ event_id: envelope.event_id,
+ event_type,
+ posted: None,
+ assignment: None,
+ project_tasks,
}
}
diff --git a/crates/agent_trigger/src/domain/sources/test.rs b/crates/agent_trigger/src/domain/sources/test.rs
index ce5c9c7750..061b818af3 100644
--- a/crates/agent_trigger/src/domain/sources/test.rs
+++ b/crates/agent_trigger/src/domain/sources/test.rs
@@ -84,9 +84,55 @@ fn the_message_source_carries_the_persisted_parent_through() {
}
#[test]
-fn the_trigger_reads_messages_and_properties() {
+fn the_trigger_reads_messages_properties_and_project_membership() {
assert_eq!(
MessageTriggerEvents::topics(),
- ["macro.messages", "macro.properties"]
+ ["macro.messages", "macro.properties", "macro.initiatives"]
);
}
+
+#[test]
+fn project_membership_events_keep_their_attribution_and_changes() {
+ use initiative::domain::{events::TaskMembershipChange, models::InitiativeId};
+ let project = InitiativeId::generate();
+ let changes = InitiativeTasksChanged {
+ attribution: Some(initiative::domain::events::InitiativeEventActor {
+ actor: sender(),
+ on_behalf_of: None,
+ }),
+ changes: vec![TaskMembershipChange {
+ task_id: "task-a".into(),
+ from: None,
+ to: Some(project),
+ }],
+ occurred_at: Utc::now(),
+ };
+ let event =
+ InitiativeMacroEvent::new(project, InitiativeTopicEvent::TasksChanged(changes.clone()));
+ let decoded = MessageTriggerEvents::decode(&record(&event))
+ .unwrap()
+ .into_trigger();
+ assert_eq!(decoded.event_type, "initiative.tasks_changed");
+ assert_eq!(decoded.project_tasks, Some(changes));
+ assert!(decoded.assignment.is_none());
+ assert!(decoded.posted.is_none());
+}
+
+#[test]
+fn project_edits_do_not_assign_existing_tasks() {
+ use initiative::domain::{events::InitiativeChange, models::InitiativeId};
+ let project = InitiativeId::generate();
+ let event = InitiativeMacroEvent::new(
+ project,
+ InitiativeTopicEvent::Updated(InitiativeChange {
+ initiative_id: project,
+ attribution: None,
+ occurred_at: Utc::now(),
+ }),
+ );
+ let decoded = MessageTriggerEvents::decode(&record(&event))
+ .unwrap()
+ .into_trigger();
+ assert!(decoded.project_tasks.is_none());
+ assert!(decoded.assignment.is_none());
+}
diff --git a/crates/properties/src/domain/error.rs b/crates/properties/src/domain/error.rs
index 4942f40e9e..50e5b4ce85 100644
--- a/crates/properties/src/domain/error.rs
+++ b/crates/properties/src/domain/error.rs
@@ -3,6 +3,11 @@
use models_properties::service::property_option::PropertyOption;
use thiserror::Error;
+/// A stored property value cannot be decoded or used for the requested mutation.
+#[derive(Debug, Error)]
+#[error("Stored property value is invalid for this operation")]
+pub(crate) struct InvalidStoredPropertyValue;
+
/// Domain error type for property operations.
#[derive(Debug, Error)]
pub enum PropertiesErr {
diff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rs
index ee304807db..8c1d824694 100644
--- a/crates/properties/src/domain/ports.rs
+++ b/crates/properties/src/domain/ports.rs
@@ -235,6 +235,16 @@ pub trait PropertiesRepo: Send + Sync + 'static {
value: Option<PropertyValue>,
) -> impl Future<Output = Result<EntityPropertyMutationSnapshot, Self::Err>> + Send;
+ /// Append entity references atomically while preserving current references.
+ /// Duplicates are ignored and the snapshot captures the locked previous value.
+ fn add_entity_property_references(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ references: Vec<EntityReference>,
+ ) -> impl Future<Output = Result<EntityPropertyMutationSnapshot, Self::Err>> + Send;
+
/// Atomically add one option to a multi-select entity property value,
/// attaching the property if needed. Re-adding a present option is deduped.
/// Composes with concurrent option changes without a lost update and returns
diff --git a/crates/properties/src/domain/service.rs b/crates/properties/src/domain/service.rs
index 852af45524..1f8a5b4d68 100644
--- a/crates/properties/src/domain/service.rs
+++ b/crates/properties/src/domain/service.rs
@@ -86,6 +86,17 @@ pub trait PropertiesService: Send + Sync + 'static {
value: Option<SetPropertyValue>,
) -> impl Future<Output = Result<EntityPropertyWithDefinition, PropertiesErr>> + Send;
+ /// Append the project's agent assignees to a newly added task, preserving
+ /// existing assignees and concurrent edits. Both capabilities must belong
+ /// to the same actor. Publishes assignment changes with the task's attribution.
+ /// The caller verifies the task's current project membership.
+ /// Documents that are no longer tasks are ignored.
+ fn inherit_project_agent_assignees(
+ &self,
+ project: &ViewReceipt,
+ task: &EditReceipt,
+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;
+
/// Add one option to a multi-select entity property value atomically.
/// Attaches the property if needed and dedupes. Validates the option belongs
/// to the (multi-select) property. Prefer this over `set_entity_property`
diff --git a/crates/properties/src/domain/service_impl.rs b/crates/properties/src/domain/service_impl.rs
index a639cd9c8b..5bc834f9bd 100644
--- a/crates/properties/src/domain/service_impl.rs
+++ b/crates/properties/src/domain/service_impl.rs
@@ -8,6 +8,7 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use activity::Actor;
+use bot_id::BotIdStr;
use document_sub_type::DocumentSubType;
use entity_access::domain::models::{
BotReceiptScope, EntityAccessAuth, EntityAccessReceipt, EntityType as AccessEntityType,
@@ -33,7 +34,7 @@ use models_properties::{EntityReference, EntityType};
use system_properties::{StatusOption, SystemPropertyKey};
use uuid::Uuid;
-use super::error::PropertiesErr;
+use super::error::{InvalidStoredPropertyValue, PropertiesErr};
use super::events::{
EntityPropertiesClearedMetadata, EntityPropertyDeletedMetadata, EntityPropertyUpdatedMetadata,
PropertyCreatedMetadata, PropertyDeletedMetadata, PropertyMacroEvent,
@@ -94,6 +95,15 @@ fn published_event_actors(access: &EditReceipt) -> PublishedEventActors {
}
}
+fn inheritance_error(error: PropertiesErr) -> PropertiesErr {
+ match error {
+ PropertiesErr::Repo(error) if error.is::<InvalidStoredPropertyValue>() => {
+ PropertiesErr::Validation("Stored assignees are invalid".to_string())
+ }
+ error => error,
+ }
+}
+
/// Implementation of [`PropertiesService`] using repository, permission,
/// notification, and event-publishing ports.
#[derive(Debug)]
@@ -752,6 +762,74 @@ where
})
}
+ #[tracing::instrument(skip_all, err)]
+ async fn inherit_project_agent_assignees(
+ &self,
+ project: &ViewReceipt,
+ task: &EditReceipt,
+ ) -> Result<(), PropertiesErr> {
+ if project.entity_type() != AccessEntityType::Initiative
+ || task.entity_type() != AccessEntityType::Document
+ {
+ return Err(PropertiesErr::Validation(
+ "Agent inheritance requires a project and a task".to_string(),
+ ));
+ }
+ let same_actor = match (project.auth(), task.auth()) {
+ (EntityAccessAuth::Authenticated(project), EntityAccessAuth::Authenticated(task)) => {
+ project == task
+ }
+ (EntityAccessAuth::Bot(project), EntityAccessAuth::Bot(task)) => project == task,
+ (EntityAccessAuth::Internal, EntityAccessAuth::Internal) => true,
+ _ => false,
+ };
+ if !same_actor {
+ return Err(PropertiesErr::PermissionDenied);
+ }
+ if self.resolve_subject(task).await?.storage_entity_type != EntityType::Task {
+ // Membership events may outlive the document's task subtype.
+ return Ok(());
+ }
+
+ let Some(PropertyValue::EntityRef(references)) = self
+ .get_system_property_value(project, SystemPropertyKey::Assignees)
+ .await
+ .map_err(inheritance_error)?
+ else {
+ return Ok(());
+ };
+ let agents = references
+ .into_iter()
+ .filter(|reference| {
+ reference.entity_type == EntityType::User
+ && BotIdStr::parse_from_str(&reference.entity_id).is_ok()
+ })
+ .collect::<Vec<_>>();
+ if agents.is_empty() {
+ return Ok(());
+ }
+
+ let mutation = self
+ .repository
+ .add_entity_property_references(
+ task.entity_id(),
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ agents,
+ )
+ .await
+ .map_err(|error| inheritance_error(anyhow::Error::from(error).into()))?;
+ if mutation.value != mutation.previous_value {
+ self.publish_property_event(Self::entity_property_updated_event(
+ &mutation.property,
+ &mutation.value,
+ &mutation.previous_value,
+ task,
+ ));
+ }
+ Ok(())
+ }
+
#[tracing::instrument(
skip(self, access),
fields(
diff --git a/crates/properties/src/domain/service_impl/task_properties.rs b/crates/properties/src/domain/service_impl/task_properties.rs
index a840afb192..cf9da56b84 100644
--- a/crates/properties/src/domain/service_impl/task_properties.rs
+++ b/crates/properties/src/domain/service_impl/task_properties.rs
@@ -40,19 +40,24 @@ where
let Some(PropertyValue::EntityRef(references)) = value else {
return Ok(());
};
- let assignee_ids = references
- .iter()
- .map(|reference| {
- if reference.entity_type != EntityType::User {
- return Err(PropertiesErr::Validation(
- "Assignees must reference users".to_string(),
- ));
- }
+ let mut assignee_ids = Vec::new();
+ for reference in references {
+ if reference.entity_type != EntityType::User {
+ return Err(PropertiesErr::Validation(
+ "Assignees must reference users or agents".to_string(),
+ ));
+ }
+ // Agents act with the delegating user's access; only human
+ // assignees receive direct project collaboration grants.
+ if BotIdStr::parse_from_str(&reference.entity_id).is_ok() {
+ continue;
+ }
+ assignee_ids.push(
MacroUserIdStr::parse_from_str(&reference.entity_id)
.map(|user_id| user_id.into_owned())
- .map_err(|error| PropertiesErr::Validation(error.to_string()))
- })
- .collect::<Result<Vec<_>, _>>()?;
+ .map_err(|error| PropertiesErr::Validation(error.to_string()))?,
+ );
+ }
if assignee_ids.is_empty() {
return Ok(());
}
diff --git a/crates/properties/src/domain/service_impl/task_properties/test.rs b/crates/properties/src/domain/service_impl/task_properties/test.rs
index 136f13c763..f54879c885 100644
--- a/crates/properties/src/domain/service_impl/task_properties/test.rs
+++ b/crates/properties/src/domain/service_impl/task_properties/test.rs
@@ -31,6 +31,27 @@ async fn agents_do_not_require_human_permission_or_notification_services() {
.unwrap();
}
+#[tokio::test]
+async fn project_agents_do_not_require_human_collaborator_grants() {
+ let service = PropertiesServiceImpl::new(
+ MockPropertiesRepo::new(),
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+ let access = EditReceipt::dangerously_assert_authenticated_user(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ &Uuid::from_u128(1).to_string(),
+ entity_access::domain::models::EntityType::Initiative,
+ );
+ service
+ .handle_initiative_assignees_property(
+ &access,
+ &Some(PropertyValue::EntityRef(vec![agent_reference()])),
+ )
+ .await
+ .unwrap();
+}
+
#[tokio::test]
async fn mixed_assignments_grant_access_and_notify_only_humans() {
let task_id = Uuid::from_u128(1);
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index 4194a1ad1b..8d7933099e 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -2,6 +2,7 @@
mod initiatives;
mod options_batch;
+mod project_agents;
use super::service_impl::PropertiesServiceImpl;
use crate::domain::error::PropertiesErr;
diff --git a/crates/properties/src/domain/test/initiatives.rs b/crates/properties/src/domain/test/initiatives.rs
index 2e86d72ab1..f75160ac4a 100644
--- a/crates/properties/src/domain/test/initiatives.rs
+++ b/crates/properties/src/domain/test/initiatives.rs
@@ -205,6 +205,10 @@ async fn assignees_share_the_initiative_and_allow_assigning_the_owner() {
references: vec![
EntityReference::new(owner.as_ref(), EntityType::User),
EntityReference::new("macro|[email protected]", EntityType::User),
+ EntityReference::new(
+ bot_id::CODEX_BOT_ID.into_storage_id().as_ref(),
+ EntityType::User,
+ ),
],
}),
)
diff --git a/crates/properties/src/domain/test/project_agents.rs b/crates/properties/src/domain/test/project_agents.rs
new file mode 100644
index 0000000000..1a1f0cf8fe
--- /dev/null
+++ b/crates/properties/src/domain/test/project_agents.rs
@@ -0,0 +1,261 @@
+use super::*;
+use crate::domain::error::InvalidStoredPropertyValue;
+use models_properties::EntityReference;
+
+fn agent() -> EntityReference {
+ EntityReference::new(
+ bot_id::CODEX_BOT_ID.into_storage_id().as_ref(),
+ EntityType::User,
+ )
+}
+
+fn human() -> EntityReference {
+ EntityReference::new("macro|[email protected]", EntityType::User)
+}
+
+fn task_repo(task_id: Uuid) -> MockPropertiesRepo {
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_document_sub_types()
+ .withf(move |ids| ids == [task_id])
+ .returning(move |_| {
+ Box::pin(async move { Ok(HashMap::from([(task_id, DocumentSubType::Task)])) })
+ });
+ repo
+}
+
+#[tokio::test]
+async fn inheritance_classifies_invalid_values_without_hiding_repository_failures() {
+ for source_read_fails in [false, true] {
+ for invalid_value in [false, true] {
+ let task_id = Uuid::from_u128(1);
+ let mut repo = task_repo(task_id);
+ let error = if invalid_value {
+ anyhow::Error::new(InvalidStoredPropertyValue)
+ } else {
+ anyhow::Error::new(std::io::Error::other("database unavailable"))
+ }
+ .context("property repository operation failed");
+ if source_read_fails {
+ repo.expect_get_entity_property_value()
+ .once()
+ .return_once(|_, _, _| Box::pin(async move { Err(error) }));
+ } else {
+ repo.expect_get_entity_property_value()
+ .once()
+ .return_once(|_, _, _| {
+ Box::pin(async { Ok(Some(PropertyValue::EntityRef(vec![agent()]))) })
+ });
+ repo.expect_add_entity_property_references()
+ .once()
+ .return_once(|_, _, _, _| Box::pin(async move { Err(error) }));
+ }
+ let events = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, events.clone());
+ let result = service
+ .inherit_project_agent_assignees(
+ &view_receipt("project", EntityType::Initiative),
+ &edit_receipt(&task_id.to_string(), EntityType::Task),
+ )
+ .await;
+ if invalid_value {
+ assert!(matches!(result, Err(PropertiesErr::Validation(_))));
+ } else {
+ assert!(
+ matches!(result, Err(PropertiesErr::Repo(error)) if error.is::<std::io::Error>())
+ );
+ }
+ assert!(events.events().is_empty());
+ }
+ }
+}
+
+#[tokio::test]
+async fn inheritance_merges_only_agents_and_emits_attributed_delta() {
+ let task_id = Uuid::from_u128(1);
+ let mut repo = task_repo(task_id);
+ repo.expect_get_entity_property_value()
+ .withf(|id, kind, property| {
+ id == "project"
+ && *kind == EntityType::Initiative
+ && *property == SystemPropertyKey::ASSIGNEES_UUID
+ })
+ .return_once(|_, _, _| {
+ Box::pin(async { Ok(Some(PropertyValue::EntityRef(vec![human(), agent()]))) })
+ });
+ repo.expect_add_entity_property_references()
+ .withf(move |id, kind, property, refs| {
+ id == task_id.to_string()
+ && *kind == EntityType::Task
+ && *property == SystemPropertyKey::ASSIGNEES_UUID
+ && refs == &[agent()]
+ })
+ .return_once(|id, kind, property, _| {
+ let snapshot = EntityPropertyMutationSnapshot {
+ previous_value: Some(PropertyValue::EntityRef(vec![human()])),
+ ..entity_property_mutation(
+ id,
+ kind,
+ property,
+ Some(PropertyValue::EntityRef(vec![human(), agent()])),
+ )
+ };
+ Box::pin(async move { Ok(snapshot) })
+ });
+ let events = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, events.clone());
+
+ service
+ .inherit_project_agent_assignees(
+ &view_receipt("project", EntityType::Initiative),
+ &edit_receipt(&task_id.to_string(), EntityType::Task),
+ )
+ .await
+ .unwrap();
+
+ let events = events.events();
+ assert_eq!(events.len(), 1);
+ let metadata = &events[0].envelope["metadata"];
+ assert_eq!(metadata["actor_user_id"], caller_user_id().as_ref());
+ assert_eq!(
+ metadata["previous_value"],
+ serde_json::to_value(PropertyValue::EntityRef(vec![human()])).unwrap()
+ );
+ assert_eq!(
+ metadata["value"],
+ serde_json::to_value(PropertyValue::EntityRef(vec![human(), agent()])).unwrap()
+ );
+}
+
+#[tokio::test]
+async fn repeated_inheritance_does_not_publish_another_assignment() {
+ let task_id = Uuid::from_u128(1);
+ let mut repo = task_repo(task_id);
+ repo.expect_get_entity_property_value()
+ .return_once(|_, _, _| {
+ Box::pin(async { Ok(Some(PropertyValue::EntityRef(vec![agent()]))) })
+ });
+ repo.expect_add_entity_property_references()
+ .return_once(|id, kind, property, _| {
+ let value = Some(PropertyValue::EntityRef(vec![agent()]));
+ let snapshot = EntityPropertyMutationSnapshot {
+ previous_value: value.clone(),
+ ..entity_property_mutation(id, kind, property, value)
+ };
+ Box::pin(async move { Ok(snapshot) })
+ });
+ let events = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, events.clone());
+ service
+ .inherit_project_agent_assignees(
+ &view_receipt("project", EntityType::Initiative),
+ &edit_receipt(&task_id.to_string(), EntityType::Task),
+ )
+ .await
+ .unwrap();
+ assert!(events.events().is_empty());
+}
+
+#[tokio::test]
+async fn inheritance_preserves_a_delegated_bot_actor() {
+ let task_id = Uuid::from_u128(1);
+ let mut repo = task_repo(task_id);
+ repo.expect_get_entity_property_value()
+ .return_once(|_, _, _| {
+ Box::pin(async { Ok(Some(PropertyValue::EntityRef(vec![agent()]))) })
+ });
+ repo.expect_add_entity_property_references()
+ .return_once(|id, kind, property, references| {
+ let snapshot = entity_property_mutation(
+ id,
+ kind,
+ property,
+ Some(PropertyValue::EntityRef(references)),
+ );
+ Box::pin(async move { Ok(snapshot) })
+ });
+ let bot_id = bot_id::MACRO_SYSTEM_BOT_ID;
+ let scope = BotReceiptScope::User {
+ acting_user: caller_user_id(),
+ };
+ let project = ViewReceipt::dangerously_assert_bot(
+ bot_id.into_storage_id(),
+ scope.clone(),
+ "project",
+ AccessEntityType::Initiative,
+ );
+ let task = EditReceipt::dangerously_assert_bot(
+ bot_id.into_storage_id(),
+ scope,
+ &task_id.to_string(),
+ AccessEntityType::Document,
+ );
+ let events = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, events.clone());
+ service
+ .inherit_project_agent_assignees(&project, &task)
+ .await
+ .unwrap();
+
+ let event = only_published_property_event(&events);
+ assert_eq!(
+ event.envelope["metadata"]["actor"],
+ bot_id.into_storage_id().as_ref(),
+ );
+ assert_eq!(
+ event.envelope["metadata"]["on_behalf_of"],
+ caller_user_id().as_ref(),
+ );
+ assert!(event.envelope["metadata"]["actor_user_id"].is_null());
+}
+
+#[tokio::test]
+async fn projects_without_agent_assignees_do_not_change_tasks() {
+ for value in [None, Some(PropertyValue::EntityRef(vec![human()]))] {
+ let task_id = Uuid::from_u128(1);
+ let mut repo = task_repo(task_id);
+ repo.expect_get_entity_property_value()
+ .return_once(|_, _, _| Box::pin(async move { Ok(value) }));
+ let events = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, events.clone());
+ service
+ .inherit_project_agent_assignees(
+ &view_receipt("project", EntityType::Initiative),
+ &edit_receipt(&task_id.to_string(), EntityType::Task),
+ )
+ .await
+ .unwrap();
+ assert!(events.events().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn inheritance_rejects_mismatched_actors_before_reading_or_writing() {
+ let service =
+ service_with_event_broker(MockPropertiesRepo::new(), RecordingEventBroker::default());
+ let result = service
+ .inherit_project_agent_assignees(
+ &view_receipt("project", EntityType::Initiative),
+ &edit_receipt_for_user(
+ &Uuid::from_u128(1).to_string(),
+ EntityType::Task,
+ ),
+ )
+ .await;
+ assert!(matches!(result, Err(PropertiesErr::PermissionDenied)));
+}
+
+#[tokio::test]
+async fn inheritance_ignores_documents_that_are_no_longer_tasks() {
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_document_sub_types()
+ .return_once(|_| Box::pin(async { Ok(HashMap::new()) }));
+ let service = service_with_event_broker(repo, RecordingEventBroker::default());
+ service
+ .inherit_project_agent_assignees(
+ &view_receipt("project", EntityType::Initiative),
+ &edit_receipt(&Uuid::from_u128(1).to_string(), EntityType::Document),
+ )
+ .await
+ .unwrap();
+}
diff --git a/crates/properties/src/outbound/entity_property_queries.rs b/crates/properties/src/outbound/entity_property_queries.rs
index 2d087d6b8c..cef3a3ce18 100644
--- a/crates/properties/src/outbound/entity_property_queries.rs
+++ b/crates/properties/src/outbound/entity_property_queries.rs
@@ -3,15 +3,26 @@
#[cfg(test)]
mod test;
+use anyhow::Context as _;
use models_properties::service::{entity_property::EntityProperty, property_value::PropertyValue};
use models_properties::{EntityReference, EntityType};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
+use crate::domain::error::InvalidStoredPropertyValue;
use crate::domain::model::{
EntityPropertyMutationSnapshot, EntityPropertyOptionSelection, EntityPropertyOptionUpdate,
};
+pub(super) fn decode_stored_property_value(
+ value: Option<serde_json::Value>,
+) -> anyhow::Result<Option<PropertyValue>> {
+ value
+ .filter(|value| !value.is_null())
+ .map(|value| serde_json::from_value(value).context(InvalidStoredPropertyValue))
+ .transpose()
+}
+
pub(super) struct EntityPropertyMutationRow {
pub(super) id: Uuid,
pub(super) entity_id: String,
@@ -82,6 +93,57 @@ async fn upsert_entity_property_in_transaction(
entity_type: EntityType,
property_definition_id: Uuid,
value: Option<PropertyValue>,
+) -> anyhow::Result<EntityPropertyMutationSnapshot> {
+ mutate_entity_property_in_transaction(
+ tx,
+ entity_id,
+ entity_type,
+ property_definition_id,
+ |_| Ok(value),
+ )
+ .await
+}
+
+/// Append references under the same locks as replacement writes so concurrent
+/// task assignments cannot overwrite each other's assignees.
+pub async fn add_entity_property_references(
+ pool: &Pool<Postgres>,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ references: Vec<EntityReference>,
+) -> anyhow::Result<EntityPropertyMutationSnapshot> {
+ let mut tx = pool.begin().await?;
+ let snapshot = mutate_entity_property_in_transaction(
+ &mut tx,
+ entity_id,
+ entity_type,
+ property_definition_id,
+ |previous| {
+ let mut current = match decode_stored_property_value(previous)? {
+ Some(PropertyValue::EntityRef(current)) => current,
+ None => Vec::new(),
+ Some(_) => return Err(InvalidStoredPropertyValue.into()),
+ };
+ for reference in references {
+ if !current.contains(&reference) {
+ current.push(reference);
+ }
+ }
+ Ok(Some(PropertyValue::EntityRef(current)))
+ },
+ )
+ .await?;
+ tx.commit().await?;
+ Ok(snapshot)
+}
+
+async fn mutate_entity_property_in_transaction(
+ tx: &mut sqlx::PgConnection,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ update: impl FnOnce(Option<serde_json::Value>) -> anyhow::Result<Option<PropertyValue>>,
) -> anyhow::Result<EntityPropertyMutationSnapshot> {
// Serialize first assignments even when no row exists to lock yet. Keep
// this separate from the UPSERT so its statement snapshot starts after
@@ -95,7 +157,7 @@ async fn upsert_entity_property_in_transaction(
// Other property operations use row locks rather than this advisory lock.
// Wait for those writers too before the UPSERT captures its previous value.
- sqlx::query_scalar!(
+ let previous = sqlx::query_scalar!(
r#"
SELECT values as "values: serde_json::Value"
FROM entity_properties
@@ -109,6 +171,8 @@ async fn upsert_entity_property_in_transaction(
.fetch_optional(&mut *tx)
.await?;
+ let value = update(previous.flatten())?;
+
let id = macro_uuid::generate_uuid_v7();
// Serialize PropertyValue to JSONB (or NULL if None)
diff --git a/crates/properties/src/outbound/entity_property_queries/test.rs b/crates/properties/src/outbound/entity_property_queries/test.rs
index 5662d8092a..e210829c4a 100644
--- a/crates/properties/src/outbound/entity_property_queries/test.rs
+++ b/crates/properties/src/outbound/entity_property_queries/test.rs
@@ -9,6 +9,174 @@ fn assignment() -> PropertyValue {
)])
}
+#[test]
+fn malformed_stored_values_have_a_typed_error_and_preserve_the_decode_failure() {
+ for value in [
+ serde_json::json!({"type": "Unknown", "value": []}),
+ serde_json::json!({"type": "EntityReference", "value": "legacy"}),
+ serde_json::json!({"type": "EntityReference", "value": [{}]}),
+ ] {
+ let error = decode_stored_property_value(Some(value)).unwrap_err();
+ assert!(error.is::<InvalidStoredPropertyValue>());
+ assert!(error.is::<serde_json::Error>());
+ }
+ assert_eq!(decode_stored_property_value(None).unwrap(), None);
+ assert_eq!(
+ decode_stored_property_value(Some(serde_json::Value::Null)).unwrap(),
+ None
+ );
+ assert_eq!(
+ decode_stored_property_value(Some(serde_json::to_value(assignment()).unwrap())).unwrap(),
+ Some(assignment())
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn inheritance_rejects_non_reference_values_without_overwriting_them(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let task_id = Uuid::now_v7().to_string();
+ let invalid = Some(PropertyValue::Str("legacy assignees".to_string()));
+ upsert_entity_property(
+ &pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ invalid.clone(),
+ )
+ .await?;
+
+ let error = add_entity_property_references(
+ &pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ vec![EntityReference::new(
+ bot_id::CODEX_BOT_ID.into_storage_id().as_ref(),
+ EntityType::User,
+ )],
+ )
+ .await
+ .unwrap_err();
+ assert!(error.is::<InvalidStoredPropertyValue>());
+
+ let repaired = upsert_entity_property(
+ &pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ Some(assignment()),
+ )
+ .await?;
+ assert_eq!(repaired.previous_value, invalid);
+ assert_eq!(repaired.value, Some(assignment()));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn inherited_agents_preserve_assignees_and_dedupe_retries(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let task_id = Uuid::now_v7().to_string();
+ let human = EntityReference::new("macro|[email protected]", EntityType::User);
+ let codex = EntityReference::new(
+ bot_id::CODEX_BOT_ID.into_storage_id().as_ref(),
+ EntityType::User,
+ );
+ let macro_agent = EntityReference::new(
+ bot_id::MACRO_NEW_BOT_ID.into_storage_id().as_ref(),
+ EntityType::User,
+ );
+ let existing = PropertyValue::EntityRef(vec![human.clone(), codex.clone()]);
+ upsert_entity_property(
+ &pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ Some(existing.clone()),
+ )
+ .await?;
+
+ let inherited = add_entity_property_references(
+ &pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ vec![codex.clone(), macro_agent.clone(), macro_agent.clone()],
+ )
+ .await?;
+ let combined = Some(PropertyValue::EntityRef(vec![
+ human,
+ codex,
+ macro_agent.clone(),
+ ]));
+ assert_eq!(inherited.previous_value, Some(existing));
+ assert_eq!(inherited.value, combined);
+
+ let repeated = add_entity_property_references(
+ &pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ vec![macro_agent],
+ )
+ .await?;
+ assert_eq!(repeated.previous_value, combined);
+ assert_eq!(repeated.value, combined);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn inherited_agents_merge_with_a_concurrent_assignment(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let task_id = Uuid::now_v7().to_string();
+ let mut tx = pool.begin().await?;
+ let blocker = sqlx::query_scalar!("SELECT pg_backend_pid() AS \"pid!\"")
+ .fetch_one(&mut *tx)
+ .await?;
+ let human = EntityReference::new("macro|[email protected]", EntityType::User);
+ let existing = PropertyValue::EntityRef(vec![human.clone()]);
+ upsert_entity_property_in_transaction(
+ &mut tx,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ Some(existing.clone()),
+ )
+ .await?;
+
+ let writer_pool = pool.clone();
+ let writer = tokio::spawn(async move {
+ add_entity_property_references(
+ &writer_pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ vec![EntityReference::new(
+ bot_id::CODEX_BOT_ID.into_storage_id().as_ref(),
+ EntityType::User,
+ )],
+ )
+ .await
+ });
+ wait_for_blocked_writer(&pool, blocker).await?;
+ tx.commit().await?;
+ let inherited = writer.await??;
+ assert_eq!(inherited.previous_value, Some(existing));
+ assert_eq!(
+ inherited.value,
+ Some(PropertyValue::EntityRef(vec![
+ human,
+ EntityReference::new(
+ bot_id::CODEX_BOT_ID.into_storage_id().as_ref(),
+ EntityType::User
+ ),
+ ]))
+ );
+ Ok(())
+}
+
async fn wait_for_blocked_writer(pool: &Pool<Postgres>, blocker: i32) -> anyhow::Result<()> {
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
diff --git a/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rs
index 3e561d10ce..4f0f4c748a 100644
--- a/crates/properties/src/outbound/properties_pg_repo.rs
+++ b/crates/properties/src/outbound/properties_pg_repo.rs
@@ -346,6 +346,24 @@ impl PropertiesRepo for PropertiesPgRepo {
.await
}
+ #[tracing::instrument(skip(self, references), err)]
+ async fn add_entity_property_references(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ references: Vec<EntityReference>,
+ ) -> Result<EntityPropertyMutationSnapshot, Self::Err> {
+ entity_property_queries::add_entity_property_references(
+ &self.pool,
+ entity_id,
+ entity_type,
+ property_definition_id,
+ references,
+ )
+ .await
+ }
+
#[tracing::instrument(skip(self))]
async fn add_entity_property_option(
&self,
@@ -572,16 +590,6 @@ impl PropertiesRepo for PropertiesPgRepo {
.fetch_optional(&self.pool)
.await?;
- match row {
- None => Ok(None),
- Some(r) => match r.values {
- None => Ok(None),
- Some(json_value) if json_value.is_null() => Ok(None),
- Some(json_value) => {
- let value: PropertyValue = serde_json::from_value(json_value)?;
- Ok(Some(value))
- }
- },
- }
+ entity_property_queries::decode_stored_property_value(row.and_then(|row| row.values))
}
}
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.md
index 2e395de960..189260d035 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/AGENT_GUIDE/tasks.md
@@ -193,6 +193,19 @@ Assigning a person to a project also adds them as a collaborator with edit acces
Clearing the assignee leaves that access in place; the owner can remove it through
Manage collaborators in Share. Removing a collaborator does not clear assignees.
+Project Assignees also offers the same agents as task Assignees. Choose an agent
+in the project composer, Overview property pills, project list, or Properties
+side panel; dismiss the picker to save. The picker explains that assigned agents
+automatically take on tasks created in or moved into the project. People and
+agents can remain assigned together. Existing agent permissions still apply:
+private agents run for their owner, and shared team agents run for team members.
+Assigning an agent to the project does not start work on tasks already in it.
+Removing the project agent stops assignment to future tasks; it does not cancel
+sessions already started for its tasks.
+For verification, create a task from the project's Tasks tab, then move another
+task into the project through `Set project…`; both should start the assigned
+agent's normal task session and show its message in the task's Discussion.
+
Overview's Description uses the shared collaborative Markdown editor and saves
automatically to the existing backing document. Edit/owner access allows typing;
view/comment access is read-only. The description is part of the native project
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index 16233e65de..d264ad94ed 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -67,6 +67,7 @@ document_storage_service_client = { path = "../../crates/document_storage_servic
lexical_mention_extractor = { path = "../../crates/lexical_mention_extractor" }
macro_service_urls = { path = "../../crates/macro_service_urls" }
messages = { path = "../../crates/messages", features = ["broker", "delivery"] }
+properties = { path = "../../crates/properties", default-features = false, features = ["outbound"] }
static_file = { path = "../../crates/static_file", features = ["attachment"] }
static_file_service_client = { path = "../../crates/static_file_service_client" }
macro_tower_layers = { path = "../../crates/macro_tower_layers" }
diff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rs
index f8e1fe1748..dd52ac5e9e 100644
--- a/services/agent_harness_service/src/trigger.rs
+++ b/services/agent_harness_service/src/trigger.rs
@@ -2,6 +2,7 @@
use agent_session::outbound::postgres::PgAgentSessionRepo;
use agent_trigger::domain::processing::process_message_event;
+use agent_trigger::domain::project_assignment::ProjectAssignmentService;
use agent_trigger::domain::service::AgentTriggerService;
use agent_trigger::domain::sources::{MessageTriggerEvents, TriggerEvents};
use agent_trigger::domain::task_assignment::process_task_assignment;
@@ -12,9 +13,12 @@ use agent_trigger::outbound::{
use bots::outbound::pg_bots_repo::PgBotsRepo;
use channels::outbound::pg_channels_repo::PgChannelsRepo;
use document_storage_service_client::DocumentStorageServiceClient;
+use entity_access::domain::{ports::EntityAccessService, service::EntityAccessServiceImpl};
+use entity_access::outbound::PgAccessRepository;
use entity_registry::OwnerGrantPolicy;
use entity_registry_db_utils::OwnedEntityRegistrar;
-use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};
+use initiative::{domain::ports::InitiativeRepo, outbound::PgInitiativeRepo};
+use kafka_util::{GroupName, InitialOffset, KafkaEventConsumer, consumer_span, record_span_error};
use lexical_client::LexicalClient;
use macro_event_broker::{
KafkaConsumerAdapter, KafkaEventPublisher, MacroEventBrokerService, MacroEventCollection,
@@ -23,6 +27,9 @@ use macro_event_broker::{
use macro_service_urls::{DocumentStorageServiceUrl, LexicalServiceUrl, StaticFileServiceUrl};
use messages::domain::api::MessageServiceApi;
use messages::outbound::pg_message_repo::PgMessageRepository;
+use properties::{
+ PermissionServiceImpl, PropertiesPgRepo, PropertiesService, PropertiesServiceImpl,
+};
use rdkafka::consumer::CommitMode;
use rdkafka::message::{BorrowedMessage, Message as _};
use sqlx::PgPool;
@@ -34,6 +41,9 @@ struct AgentTriggerConsumerGroup;
impl GroupName for AgentTriggerConsumerGroup {
const GROUP_NAME: &'static str = "agent-trigger-service";
+ // Existing partitions resume committed offsets. Newly subscribed topics
+ // start with future events, without assigning agents to historical tasks.
+ const INITIAL_OFFSET: InitialOffset = InitialOffset::Latest;
}
/// The concrete trigger service this binary composes.
@@ -56,6 +66,20 @@ type ChannelTypes = ChannelRepoTypeLookup<PgChannelsRepo>;
type TriggerKafkaAdapter<M> = KafkaConsumerAdapter<AgentTriggerConsumerGroup, M>;
type TriggerConsumer<M> = MacroEventConsumerService<M, TriggerKafkaAdapter<M>>;
+// Project inheritance adds agents only, which do not receive human notifications.
+struct SilentAssignmentNotifications;
+
+impl properties::NotificationService for SilentAssignmentNotifications {
+ type Err = anyhow::Error;
+
+ async fn send_task_assigned<'a>(
+ &self,
+ _: properties::domain::model::TaskAssignedNotification<'a>,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+}
+
fn commit_message<M: MacroEventCollection + 'static>(
consumer: &TriggerConsumer<M>,
message: &BorrowedMessage<'_>,
@@ -150,11 +174,26 @@ async fn run(
),
)
.with_admission(admission);
- let channel_types = ChannelRepoTypeLookup::new(PgChannelsRepo::new(pool));
+ let channel_types = ChannelRepoTypeLookup::new(PgChannelsRepo::new(pool.clone()));
let publisher = MacroEventBrokerService::new(
KafkaEventPublisher::new(&kafka_brokers)?,
macro_event_broker::GlobalSpawner,
);
+ let project_assignments = ProjectAssignmentService::new(
+ PropertiesServiceImpl::new(
+ PropertiesPgRepo::new(pool.clone()),
+ Some(PermissionServiceImpl::new(
+ pool.clone(),
+ Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ pool.clone(),
+ ))),
+ )),
+ None::<SilentAssignmentNotifications>,
+ )
+ .with_event_broker(publisher.clone()),
+ PgInitiativeRepo::new(pool.clone()),
+ EntityAccessServiceImpl::new(PgAccessRepository::new(pool)),
+ );
let consumer = KafkaEventConsumer::<AgentTriggerConsumerGroup>::from_env(&kafka_brokers)?;
let consumer = KafkaConsumerAdapter::<AgentTriggerConsumerGroup, ()>::new(consumer);
consume::<MessageTriggerEvents>(
@@ -164,6 +203,7 @@ async fn run(
&channel_types,
messages.as_ref(),
&task_context,
+ &project_assignments,
)
.await
}
@@ -176,6 +216,11 @@ async fn consume<Events: TriggerEvents>(
channel_types: &ChannelTypes,
messages: &dyn MessageServiceApi,
task_context: &DssTaskAssignmentContext,
+ project_assignments: &ProjectAssignmentService<
+ impl PropertiesService,
+ impl InitiativeRepo,
+ impl EntityAccessService,
+ >,
) -> anyhow::Result<()> {
let consumer = consumer
.subscribe::<Events>()
@@ -225,6 +270,9 @@ async fn consume<Events: TriggerEvents>(
process_task_assignment(trigger, publisher, messages, task_context, assignment)
.await?;
}
+ if let Some(changes) = &decoded.project_tasks {
+ project_assignments.process(changes).await?;
+ }
commit_message(&consumer, kafka_message)?;
Ok(())
}
diff --git a/services/agent_trigger_service/Cargo.toml b/services/agent_trigger_service/Cargo.toml
index f14fdc7000..5751e48709 100644
--- a/services/agent_trigger_service/Cargo.toml
+++ b/services/agent_trigger_service/Cargo.toml
@@ -34,6 +34,7 @@ macro_env_var = { path = "../../crates/macro_env_var" }
macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }
macro_service_urls = { path = "../../crates/macro_service_urls" }
messages = { path = "../../crates/messages", features = ["broker", "delivery", "outbound"] }
+properties = { path = "../../crates/properties", default-features = false, features = ["outbound"] }
rdkafka = { workspace = true }
rootcause = { workspace = true }
serde_json = { workspace = true }
diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rs
index 69e1658327..0e32f0ab70 100644
--- a/services/agent_trigger_service/src/main.rs
+++ b/services/agent_trigger_service/src/main.rs
@@ -8,6 +8,7 @@ mod config;
use agent_session::outbound::postgres::PgAgentSessionRepo;
use agent_trigger::domain::processing::process_message_event;
+use agent_trigger::domain::project_assignment::ProjectAssignmentService;
use agent_trigger::domain::service::AgentTriggerService;
use agent_trigger::domain::sources::{MessageTriggerEvents, TriggerEvents};
use agent_trigger::domain::task_assignment::process_task_assignment;
@@ -21,9 +22,12 @@ use channels::outbound::pg_channels_repo::PgChannelsRepo;
use config::Config;
use connection_gateway_client::client::ConnectionGatewayClient;
use document_storage_service_client::DocumentStorageServiceClient;
+use entity_access::domain::{ports::EntityAccessService, service::EntityAccessServiceImpl};
+use entity_access::outbound::PgAccessRepository;
use entity_registry::OwnerGrantPolicy;
use entity_registry_db_utils::OwnedEntityRegistrar;
-use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};
+use initiative::{domain::ports::InitiativeRepo, outbound::PgInitiativeRepo};
+use kafka_util::{GroupName, InitialOffset, KafkaEventConsumer, consumer_span, record_span_error};
use lexical_client::LexicalClient;
use macro_entrypoint::{MacroEntrypoint, shutdown_signal};
use macro_event_broker::{
@@ -35,6 +39,9 @@ use macro_service_urls::{
};
use messages::domain::api::MessageCommands;
use messages::outbound::pg_message_repo::PgMessageRepository;
+use properties::{
+ PermissionServiceImpl, PropertiesPgRepo, PropertiesService, PropertiesServiceImpl,
+};
use rdkafka::consumer::CommitMode;
use rdkafka::message::{BorrowedMessage, Message as _};
use sqlx::postgres::PgPoolOptions;
@@ -45,6 +52,9 @@ struct AgentTriggerConsumerGroup;
impl GroupName for AgentTriggerConsumerGroup {
const GROUP_NAME: &'static str = "agent-trigger-service";
+ // Existing partitions resume committed offsets. Newly subscribed topics
+ // start with future events, without assigning agents to historical tasks.
+ const INITIAL_OFFSET: InitialOffset = InitialOffset::Latest;
}
/// The concrete trigger service this binary composes.
@@ -80,6 +90,17 @@ impl messages::domain::delivery::DiscussionNotifier for SilentAssignmentNotifica
}
}
+impl properties::NotificationService for SilentAssignmentNotifications {
+ type Err = anyhow::Error;
+
+ async fn send_task_assigned<'a>(
+ &self,
+ _: properties::domain::model::TaskAssignedNotification<'a>,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+}
+
fn commit_message<M: MacroEventCollection + 'static>(
consumer: &TriggerConsumer<M>,
message: &BorrowedMessage<'_>,
@@ -158,6 +179,21 @@ async fn run() -> anyhow::Result<()> {
KafkaEventPublisher::new(config.kafka_brokers.as_ref())?,
macro_event_broker::GlobalSpawner,
);
+ let project_assignments = ProjectAssignmentService::new(
+ PropertiesServiceImpl::new(
+ PropertiesPgRepo::new(pool.clone()),
+ Some(PermissionServiceImpl::new(
+ pool.clone(),
+ Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ pool.clone(),
+ ))),
+ )),
+ None::<SilentAssignmentNotifications>,
+ )
+ .with_event_broker(publisher.clone()),
+ PgInitiativeRepo::new(pool.clone()),
+ EntityAccessServiceImpl::new(PgAccessRepository::new(pool.clone())),
+ );
let discussion_delivery = messages::domain::delivery::DiscussionDelivery::new(
messages::outbound::pg_discussion_context::PgDiscussionContext(pool.clone()),
messages::outbound::entity_access_audience::EntityAccessMessageAudience(
@@ -192,6 +228,7 @@ async fn run() -> anyhow::Result<()> {
&channel_types,
&messages,
&task_context,
+ &project_assignments,
)
.await
}
@@ -204,6 +241,11 @@ async fn consume<Events: TriggerEvents>(
channel_types: &ChannelTypes,
messages: &dyn MessageCommands,
task_context: &DssTaskAssignmentContext,
+ project_assignments: &ProjectAssignmentService<
+ impl PropertiesService,
+ impl InitiativeRepo,
+ impl EntityAccessService,
+ >,
) -> anyhow::Result<()> {
let consumer = consumer
.subscribe::<Events>()
@@ -258,6 +300,9 @@ async fn consume<Events: TriggerEvents>(
if let Some(assignment) = &decoded.assignment {
process_task_assignment(trigger, publisher, messages, task_context, assignment).await?;
}
+ if let Some(changes) = &decoded.project_tasks {
+ project_assignments.process(changes).await?;
+ }
commit_message(&consumer, kafka_message)?;
Ok(())
}