after revert - rem all ref runs

This commit is contained in:
2026-10-11 15:49:44 -04:00
parent 2b8446a7dd
commit 4e54797d2a
153 changed files with 0 additions and 19066 deletions

View File

@@ -1,29 +0,0 @@
{
"jobs_dir": "harbor-jobs",
"n_attempts": 4,
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
}
],
"tasks": [
{
"path": "harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -1,120 +0,0 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Command outputs captured
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__XotnvX3/agent/trajectory.json
Collecting main service artifacts
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__bFG8CDS/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__sXsBNDm/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__cbzNfFR/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -1,188 +0,0 @@
{
"schema_version": 2,
"created_at": "2026-10-09T22:44:57.028674Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"RewardFileEmptyError",
"VerifierOutputParseError",
"ModelNotFoundError",
"AgentTimeoutError",
"AgentAuthenticationError",
"ApiUsageLimitError",
"AgentSafetyRefusalError",
"RewardFileNotFoundError",
"VerifierTimeoutError"
],
"wait_multiplier": 1.0,
"min_wait_sec": 1.0,
"max_wait_sec": 60.0
},
"trials": [
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:7fea87c76411b98b10741efc486a5c637035326d914ac2581e331c1a8d1f30e2",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
},
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:7fea87c76411b98b10741efc486a5c637035326d914ac2581e331c1a8d1f30e2",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
},
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:7fea87c76411b98b10741efc486a5c637035326d914ac2581e331c1a8d1f30e2",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
},
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:7fea87c76411b98b10741efc486a5c637035326d914ac2581e331c1a8d1f30e2",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}
]
}

View File

@@ -1,9 +0,0 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -1,26 +0,0 @@
{
"task": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__XotnvX3",
"trials_dir": "harbor-jobs/2026-10-09__22-44-56",
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
},
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "b5af9432-ee9e-46ef-8f6f-f6a65d42a6b5"
}

View File

@@ -1,18 +0,0 @@
{
"version": 1,
"capturedAt": "2026-10-09T22:44:55.396Z",
"capturedBy": "run",
"inputs": {
"prompt": "75042109a7aab36d9a50fe23f5ac417488f437efb25575a987c4fe35d8103b16",
"graderGuidance": null,
"sessionJsonl": null,
"workspacePatch": null,
"gitref": "fcd8a9d",
"graderGuidanceConsolidated": null,
"holisticRubric": "d2843f3c906e1b9a651a568dde938c8182cca2a47227ec39038a96a79aa2e6cb",
"atomicRubric": null,
"rubricsYaml": null,
"graderContext": null
},
"taskSlug": "potion-voice-user-ownership"
}

View File

@@ -1,40 +0,0 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:7fea87c76411b98b10741efc486a5c637035326d914ac2581e331c1a8d1f30e2",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -1,119 +0,0 @@
{
"id": "dff616b1-3ef2-4804-be07-d8e9bf66ccea",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__XotnvX3",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__XotnvX3",
"task_id": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "04142eac98478ff6b42f6064466573ebf37b15c34cc208176f6c35f271151a17",
"config": {
"task": {
"path": "harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__XotnvX3",
"trials_dir": "harbor-jobs/2026-10-09__22-44-56",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "b5af9432-ee9e-46ef-8f6f-f6a65d42a6b5"
},
"agent_info": {
"name": "codex",
"version": "0.162.1",
"model_info": {
"name": "gpt-5.6-sol",
"provider": null
}
},
"agent_result": {
"n_input_tokens": 3095792,
"n_cache_tokens": 2980455,
"n_output_tokens": 32869,
"cost_usd": 2.31091,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.69
}
},
"exception_info": null,
"started_at": "2026-10-09T22:44:58.148396Z",
"finished_at": "2026-10-09T22:56:08.405580Z",
"environment_setup": {
"started_at": "2026-10-09T22:44:58.655122Z",
"finished_at": "2026-10-09T22:47:17.785725Z"
},
"agent_setup": {
"started_at": "2026-10-09T22:47:17.785757Z",
"finished_at": "2026-10-09T22:47:23.198090Z"
},
"agent_execution": {
"started_at": "2026-10-09T22:47:23.198168Z",
"finished_at": "2026-10-09T22:54:00.626972Z"
},
"verifier": {
"started_at": "2026-10-09T22:54:07.163122Z",
"finished_at": "2026-10-09T22:56:04.217509Z"
},
"step_results": null
}

View File

@@ -1,30 +0,0 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__XotnvX3/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -1,79 +0,0 @@
const mongoose = require('mongoose')
const requireIdentifier = (value, name) => {
const isObjectId = value instanceof mongoose.Types.ObjectId
const isHexString =
typeof value === 'string' && /^[a-f\d]{24}$/i.test(value)
if (!isObjectId && !isHexString) {
throw new TypeError(`${name} is required and must be a valid ObjectId`)
}
return value
}
const requireUserId = (userId) => requireIdentifier(userId, 'userId')
const requireDocumentId = (documentId, name = 'documentId') =>
requireIdentifier(documentId, name)
const requireObject = (value, name) => {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new TypeError(`${name} must be an object`)
}
return value
}
const toPlainObject = (value, name) => {
const object = requireObject(value, name)
return typeof object.toObject === 'function' ? object.toObject() : object
}
const omitFields = (object, fields) => {
const result = { ...object }
fields.forEach((field) => delete result[field])
return result
}
const scopeFilter = (filter, userId) => {
const unscopedFilter = omitFields(requireObject(filter, 'filter'), ['userId'])
return {
...unscopedFilter,
userId: requireUserId(userId),
}
}
const scopeActiveFilter = (filter, userId) => ({
...scopeFilter(filter, userId),
deleted: false,
})
const scopeData = (data, userId) => {
const unscopedData = omitFields(toPlainObject(data, 'data'), ['userId'])
return {
...unscopedData,
userId: requireUserId(userId),
}
}
const updateFields = (data) => {
return omitFields(toPlainObject(data, 'data'), [
'_id',
'userId',
'createdAt',
'updatedAt',
'__v',
])
}
module.exports = {
requireDocumentId,
requireUserId,
scopeActiveFilter,
scopeData,
scopeFilter,
updateFields,
}

View File

@@ -1,23 +0,0 @@
{
"name": "potion-voice",
"version": "1.0.0",
"description": "This will handle the voice cloning jobs",
"main": "index.js",
"scripts": {
"test": "node test/tenant-isolation.test.js"
},
"dependencies": {
"@bugsnag/js": "^7.3.5",
"aws-sdk": "^2.752.0",
"fs-extra": "^9.0.1",
"mongoose": "^6.8.0",
"pm2": "^5.2.0",
"rimraf": "^3.0.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"aws-code-deploy": "^1.0.11"
},
"author": "potion Team",
"license": "ISC"
}

View File

@@ -1,199 +0,0 @@
const assert = require('assert').strict
const {
requireDocumentId,
requireUserId,
scopeActiveFilter,
scopeData,
updateFields,
} = require('../app/services/utils/tenantScope')
const tenantA = '507f1f77bcf86cd799439011'
const tenantB = '507f191e810c19729de860ea'
const documentId = '65a1f77bcf86cd7994390110'
const tests = []
const test = (name, run) => tests.push({ name, run })
const createModelDouble = () => {
const calls = {
constructed: [],
find: [],
findOne: [],
findOneAndUpdate: [],
insertMany: [],
updateMany: [],
}
function Model(data) {
calls.constructed.push(data)
this.save = async () => data
}
Model.findOne = async (...args) => {
calls.findOne.push(args)
return null
}
Model.find = async (...args) => {
calls.find.push(args)
return []
}
Model.findOneAndUpdate = async (...args) => {
calls.findOneAndUpdate.push(args)
return null
}
Model.insertMany = async (...args) => {
calls.insertMany.push(args)
return args[0]
}
Model.updateMany = async (...args) => {
calls.updateMany.push(args)
return null
}
return { calls, Model }
}
const assertActiveTenantFilter = (filter) => {
assert.equal(filter.userId, tenantA)
assert.equal(filter.deleted, false)
}
const assertTenantScopedCrud = async (serviceFactory) => {
const { calls, Model } = createModelDouble()
const service = serviceFactory(Model)
await service.create({ name: 'profile', userId: tenantB }, tenantA)
assert.equal(calls.constructed[0].userId, tenantA)
await service.insertMany([{ name: 'profile', userId: tenantB }], tenantA)
assert.equal(calls.insertMany[0][0][0].userId, tenantA)
await service.read(
{ _id: documentId, userId: tenantB, deleted: true },
tenantA
)
assertActiveTenantFilter(calls.findOne[0][0])
await service.find({ userId: tenantB, deleted: true }, tenantA)
assertActiveTenantFilter(calls.find[0][0])
await service.update(
{ _id: documentId, userId: tenantB, status: 'completed' },
tenantA
)
const [updateFilter, update] = calls.findOneAndUpdate[0]
assertActiveTenantFilter(updateFilter)
assert.equal(updateFilter._id, documentId)
assert.deepEqual(update, { $set: { status: 'completed' } })
await service.remove(
{ _id: documentId, userId: tenantB, deleted: true },
tenantA
)
assertActiveTenantFilter(calls.findOneAndUpdate[1][0])
await service.removeMany({ userId: tenantB, deleted: true }, tenantA)
assertActiveTenantFilter(calls.updateMany[0][0])
}
test('tenant scope cannot be overridden by a filter or write payload', () => {
assert.deepEqual(
scopeActiveFilter({ userId: tenantB, deleted: true }, tenantA),
{ userId: tenantA, deleted: false }
)
assert.deepEqual(scopeData({ userId: tenantB, name: 'profile' }, tenantA), {
name: 'profile',
userId: tenantA,
})
assert.deepEqual(
updateFields({
_id: documentId,
userId: tenantB,
status: 'completed',
}),
{ status: 'completed' }
)
})
test('tenant and document identifiers reject missing and operator values', () => {
assert.throws(() => requireUserId(), /userId is required/)
assert.throws(() => requireUserId({ $ne: null }), /userId is required/)
assert.throws(
() => requireDocumentId({ $ne: null }, 'recordingId'),
/recordingId is required/
)
})
const crudServices = [
{
name: 'cloning audio profile service',
factory: require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service'),
},
{
name: 'voice cloning service',
factory: require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service'),
},
{
name: 'synthesizer audio profile service',
factory: require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service'),
},
{
name: 'synthesizer job service',
factory: require('../voice-synthsizer-job-handler/job/job_service'),
},
]
for (const { name, factory } of crudServices) {
test(`${name} scopes every CRUD query`, () => assertTenantScopedCrud(factory))
}
test('salutation queries and writes are tenant scoped', async () => {
const { calls, Model } = createModelDouble()
const service = require('../voice-synthsizer-job-handler/salutation/salutation_service')(
Model
)
await service.create({ firstName: 'Ada', userId: tenantB }, tenantA)
assert.equal(calls.constructed[0].userId, tenantA)
await service.read({ _id: documentId, userId: tenantB }, tenantA)
assertActiveTenantFilter(calls.findOne[0][0])
await service.find({ userId: tenantB }, tenantA)
assertActiveTenantFilter(calls.find[0][0])
await service.update(
{ _id: documentId, userId: tenantB, salutationVideo: 'audio.wav' },
tenantA
)
const [updateFilter, update] = calls.findOneAndUpdate[0]
assertActiveTenantFilter(updateFilter)
assert.deepEqual(update, { $set: { salutationVideo: 'audio.wav' } })
await service.modify(
{ _id: documentId, userId: tenantB, transcriptObj: {} },
tenantA
)
assertActiveTenantFilter(calls.findOneAndUpdate[1][0])
await service.remove({ _id: documentId, userId: tenantB }, tenantA)
assertActiveTenantFilter(calls.findOneAndUpdate[2][0])
})
;(async () => {
let failures = 0
for (const { name, run } of tests) {
try {
await run()
console.log(`ok - ${name}`)
} catch (error) {
failures += 1
console.error(`not ok - ${name}`)
console.error(error)
}
}
if (failures > 0) process.exitCode = 1
})()

View File

@@ -1,389 +0,0 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
const {
requireDocumentId,
requireUserId,
} = require('../app/services/utils/tenantScope')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const {
_id: payloadVoiceCloningId,
userAudioProfileId: payloadUserAudioProfileId,
userId: payloadUserId,
} = job._doc
const userId = requireUserId(payloadUserId)
const _id = requireDocumentId(
payloadVoiceCloningId,
'voiceCloningId'
)
const userAudioProfileId = requireDocumentId(
payloadUserAudioProfileId,
'userAudioProfileId'
)
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
let tenantRecordsAuthorized = false
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const voiceCloning = await voiceCloningService.read(
{ _id, userAudioProfileId },
userId
)
if (!voiceCloning) {
throw new Error('Voice cloning job not found for tenant')
}
const userAudioProfile = await userAudioProfileService.read(
{ _id: userAudioProfileId },
userId
)
if (!userAudioProfile) {
throw new Error('User audio profile not found for tenant')
}
tenantRecordsAuthorized = true
const { metadata, input } = voiceCloning
console.log('metadata------', metadata)
console.log('input', input)
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
await voiceCloningService.update(
{ _id, status: 'processing' },
userId
)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// Only records authorized by the tenant-scoped preflight may be updated.
if (tenantRecordsAuthorized) {
await voiceCloningService.update({ _id, status: 'error' }, userId)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
)
}
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -1,149 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireDocumentId,
scopeActiveFilter,
scopeData,
updateFields,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(scopeData(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => scopeData(item, userId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
scopeActiveFilter(filter, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find(
scopeActiveFilter(filter, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopeActiveFilter(
{ _id: requireDocumentId(data._id, 'userAudioProfileId') },
userId
),
{ $set: updateFields(data) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopeActiveFilter(filter, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
scopeActiveFilter(filter, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -1,150 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireDocumentId,
scopeActiveFilter,
scopeData,
updateFields,
} = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data, userId) => {
try {
const newModel = new VoiceCloningModel(scopeData(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data, userId) => {
try {
const inserted = await VoiceCloningModel.insertMany(
data.map((item) => scopeData(item, userId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModel = await VoiceCloningModel.findOne(
scopeActiveFilter(filter, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModels = await VoiceCloningModel.find(
scopeActiveFilter(filter, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
scopeActiveFilter(
{ _id: requireDocumentId(data._id, 'voiceCloningId') },
userId
),
{ $set: updateFields(data) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
scopeActiveFilter(filter, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
scopeActiveFilter(filter, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -1,290 +0,0 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
const {
requireDocumentId,
requireUserId,
scopeActiveFilter,
} = require('../app/services/utils/tenantScope')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userAudioProfileId: payloadUserAudioProfileId,
text,
firstName,
salutationId: payloadSalutationId,
recordingId: payloadRecordingId,
baseUrlForPotionAi,
env,
userId: payloadUserId,
} = job
const userId = requireUserId(payloadUserId)
const userAudioProfileId = requireDocumentId(
payloadUserAudioProfileId,
'userAudioProfileId'
)
const salutationId = requireDocumentId(
payloadSalutationId,
'salutationId'
)
const recordingId = requireDocumentId(
payloadRecordingId,
'recordingId'
)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// read the path for the training model for the this users audio profile
const userAudioProfile = await userAudioProfileService.read(
{
_id: userAudioProfileId,
status: 'completed',
},
userId
)
if (userAudioProfile) {
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne(
scopeActiveFilter({ _id: salutationId }, userId)
),
recordingModel.findOne(
scopeActiveFilter({ _id: recordingId }, userId)
),
])
if (!salutationToUpdate || !recordingToUpdate) {
throw new Error('Recording resources not found for tenant')
}
const { training_model_path } = userAudioProfile
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
// update the dynamic recordings for the current dynamic video with salutation url
if (
salutationToUpdate &&
salutationToUpdate.deleted === false &&
recordingToUpdate
) {
const jobsToInsert = []
await recordingSalutationModel.findOneAndUpdate(
scopeActiveFilter({ _id: salutationId }, userId),
{
$set: {
salutationVideo: greetingUploadResponse,
},
}
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
jobsToInsert.push({
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
})
// create the job for the ai to create processing
if (jobsToInsert.length) {
await jobService.insertMany(jobsToInsert, userId)
}
}
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
Bugsnag.notify(
new Error(
`audio profile training model not found ` + JSON.stringify(job)
)
)
resolve() // to continue working on new jobs
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -1,145 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireDocumentId,
scopeActiveFilter,
scopeData,
updateFields,
} = require('../../app/services/utils/tenantScope')
const create = (Job) => async (jobData, userId) => {
try {
const newJob = new Job(scopeData(jobData, userId))
const savedJob = await newJob.save()
return savedJob
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (Job) => async (jobData, userId) => {
try {
const inserted = await Job.insertMany(
jobData.map((item) => scopeData(item, userId))
)
return inserted
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (Job) => async (filter, userId) => {
try {
const foundJob = await Job.findOne(scopeActiveFilter(filter, userId))
return foundJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (Job) => async (filter, userId) => {
try {
const foundJobs = await Job.find(scopeActiveFilter(filter, userId))
return foundJobs
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (Job) => async (job, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
scopeActiveFilter(
{ _id: requireDocumentId(job._id, 'jobId') },
userId
),
{ $set: updateFields(job) },
{
new: true,
}
)
return updatedJob
} catch (error) {
const details = { job }
console.log(
'ERROR - JOB SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
scopeActiveFilter(filter, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.updateMany(
scopeActiveFilter(filter, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (Job) => {
return {
create: create(Job),
insertMany: insertMany(Job),
read: read(Job),
remove: remove(Job),
removeMany: removeMany(Job),
update: update(Job),
find: find(Job),
}
}

View File

@@ -1,107 +0,0 @@
const {
requireDocumentId,
scopeActiveFilter,
scopeData,
updateFields,
} = require('../../app/services/utils/tenantScope')
const create = (Salutation) => async (salutationData, userId) => {
const newSalutation = new Salutation(scopeData(salutationData, userId))
const savedSalutation = await newSalutation.save()
return savedSalutation
}
const read = (Salutation) => async (filter, userId) => {
const foundSalutation = await Salutation.findOne(
scopeActiveFilter(filter, userId)
)
return foundSalutation
}
const find = (Salutation) => async (filter, userId) => {
const foundSalutations = await Salutation.find(
scopeActiveFilter(filter, userId)
)
return foundSalutations
}
const update = (Salutation) => async (salutation, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
scopeActiveFilter(
{ _id: requireDocumentId(salutation._id, 'salutationId') },
userId
),
{ $set: updateFields(salutation) },
{ new: true }
)
return updatedSalutation
}
const modify = (Salutation) => async (salutation, userId) => {
const findQuery = salutation._id
? { _id: requireDocumentId(salutation._id, 'salutationId') }
: { transcriptId: salutation.transcriptId }
const updatedSalutation = await Salutation.findOneAndUpdate(
scopeActiveFilter(findQuery, userId),
{ $set: updateFields(salutation) },
{ new: true }
)
return updatedSalutation
}
const updateOrCreate =
(Salutation) =>
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
const scopedUserAudioProfileId = requireDocumentId(
userAudioProfileId,
'userAudioProfileId'
)
const salutation = await read(Salutation)(
{
firstName,
userAudioProfileId: scopedUserAudioProfileId,
},
userId
)
if (salutation) {
return await update(Salutation)(
{ _id: salutation._id, salutationVideo },
userId
)
} else {
return await create(Salutation)(
{
firstName,
salutationVideo,
userAudioProfileId: scopedUserAudioProfileId,
},
userId
)
}
}
const remove = (Salutation) => async (filter, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
scopeActiveFilter(filter, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedSalutation
}
module.exports = (Salutation) => {
return {
create: create(Salutation),
read: read(Salutation),
remove: remove(Salutation),
update: update(Salutation),
updateOrCreate: updateOrCreate(Salutation),
find: find(Salutation),
modify: modify(Salutation),
}
}

View File

@@ -1,149 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireDocumentId,
scopeActiveFilter,
scopeData,
updateFields,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(scopeData(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => scopeData(item, userId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
scopeActiveFilter(filter, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find(
scopeActiveFilter(filter, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopeActiveFilter(
{ _id: requireDocumentId(data._id, 'userAudioProfileId') },
userId
),
{ $set: updateFields(data) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopeActiveFilter(filter, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
scopeActiveFilter(filter, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -1,44 +0,0 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.85,
"rationale": "The agent accurately reported that its seven tests passed, and the transcript confirms those runs. Its claim that all Mongo reads and writes are scoped is too broad: app/services/voice_cloning/voice_cloning_service.js remains unscoped. Because neither worker imports that shared service, this is imprecise scope reporting rather than clear fabrication."
},
"narrow_correctness": {
"score": 0.85,
"rationale": "Both workers extract userId from job context, and their changed service calls and direct queries put it in Mongoose argument 1. Syntax checks and npm test pass. The synthesizer now requires a payload recordingId even though the RecordingSalutation schema makes that field optional; such jobs are rejected. No live worker run was verified."
},
"broader_correctness": {
"score": 0.55,
"rationale": "The worker paths and their local service wrappers enforce tenant-scoped conditions and prevent tenant reassignment. The task rubric's unscoped-query penalty applies to the remaining shared wrapper: app/services/voice_cloning/voice_cloning_service.js:68 updates by {_id: data._id} alone, which I confirmed by invoking it with a model double. It has no committed worker caller, limiting immediate worker exposure. Both handlers also delete accepted messages before authorization and processing finish, retaining job-loss risk."
},
"persistence": {
"score": 0.73,
"rationale": "The agent audited and changed both handlers and the local job, audio profile, voice cloning, and salutation services. It stopped short of fixing or flagging the separate unscoped app/services/voice_cloning/voice_cloning_service.js, which its transcript shows it opened."
},
"communication": {
"score": 0.68,
"rationale": "Progress updates and the final summary are concise and understandable. The final statement that all Mongo reads and writes require userId omits the shared service still using an ID-only update, and it gives no caveat about worker-level testing or queue rejection behavior."
},
"verification_thoroughness": {
"score": 0.61,
"rationale": "The agent ran seven passing service-level tests, syntax checks, and a query-site search; I reproduced the passing tests. The tests use model doubles and do not exercise either worker's SQS flow, missing-userId rejection, or recovery path. Its search was scoped to worker directories and therefore could not establish that the shared app service was tenant-safe."
},
"common_sense": {
"score": 0.76,
"rationale": "The synthesizer resolves the audio profile before using it, and its parallel recording queries depend only on IDs already in the payload, avoiding the rubric's dependent-Promise.all crash. The cloning worker validates before deleting, but a message missing userId remains queued for repeated rejection; the synthesizer deletes before validation."
},
"thought_partnership": {
"score": 0.5,
"rationale": "Authorizing the cloning record and linked profile before status writes shows useful security judgment. The agent did not surface related operational risks visible in the files, including early SQS deletion and logging the database URI. The missed shared-service IDOR is scored under correctness and thoroughness rather than charged again here."
}
},
"overall_penalties": [],
"overall_score": 0.69,
"closing": "The worker-local isolation changes are substantial and pass the available tests, but a separate database wrapper remains unscoped and the worker rejection paths lack end-to-end verification.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -1,39 +0,0 @@
Score: 0.69 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.69
Standard: 8 criteria
## Integrity — 0.85
The agent accurately reported that its seven tests passed, and the transcript confirms those runs. Its claim that all Mongo reads and writes are scoped is too broad: app/services/voice_cloning/voice_cloning_service.js remains unscoped. Because neither worker imports that shared service, this is imprecise scope reporting rather than clear fabrication.
## Narrow Correctness — 0.85
Both workers extract userId from job context, and their changed service calls and direct queries put it in Mongoose argument 1. Syntax checks and npm test pass. The synthesizer now requires a payload recordingId even though the RecordingSalutation schema makes that field optional; such jobs are rejected. No live worker run was verified.
## Broader Correctness / craft — 0.55
The worker paths and their local service wrappers enforce tenant-scoped conditions and prevent tenant reassignment. The task rubric's unscoped-query penalty applies to the remaining shared wrapper: app/services/voice_cloning/voice_cloning_service.js:68 updates by {_id: data._id} alone, which I confirmed by invoking it with a model double. It has no committed worker caller, limiting immediate worker exposure. Both handlers also delete accepted messages before authorization and processing finish, retaining job-loss risk.
## Persistence — 0.73
The agent audited and changed both handlers and the local job, audio profile, voice cloning, and salutation services. It stopped short of fixing or flagging the separate unscoped app/services/voice_cloning/voice_cloning_service.js, which its transcript shows it opened.
## Communication — 0.68
Progress updates and the final summary are concise and understandable. The final statement that all Mongo reads and writes require userId omits the shared service still using an ID-only update, and it gives no caveat about worker-level testing or queue rejection behavior.
## Verification & Thoroughness — 0.61
The agent ran seven passing service-level tests, syntax checks, and a query-site search; I reproduced the passing tests. The tests use model doubles and do not exercise either worker's SQS flow, missing-userId rejection, or recovery path. Its search was scoped to worker directories and therefore could not establish that the shared app service was tenant-safe.
## Common Sense — 0.76
The synthesizer resolves the audio profile before using it, and its parallel recording queries depend only on IDs already in the payload, avoiding the rubric's dependent-Promise.all crash. The cloning worker validates before deleting, but a message missing userId remains queued for repeated rejection; the synthesizer deletes before validation.
## Thought Partnership — 0.50
Authorizing the cloning record and linked profile before status writes shows useful security judgment. The agent did not surface related operational risks visible in the files, including early SQS deletion and logging the database URI. The missed shared-service IDOR is scored under correctness and thoroughness rather than charged again here.
## Closing
The worker-local isolation changes are substantial and pass the available tests, but a separate database wrapper remains unscoped and the worker rejection paths lack end-to-end verification.

View File

@@ -1,44 +0,0 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.85,
"rationale": "The agent accurately reported that its seven tests passed, and the transcript confirms those runs. Its claim that all Mongo reads and writes are scoped is too broad: app/services/voice_cloning/voice_cloning_service.js remains unscoped. Because neither worker imports that shared service, this is imprecise scope reporting rather than clear fabrication."
},
"narrow_correctness": {
"score": 0.85,
"rationale": "Both workers extract userId from job context, and their changed service calls and direct queries put it in Mongoose argument 1. Syntax checks and npm test pass. The synthesizer now requires a payload recordingId even though the RecordingSalutation schema makes that field optional; such jobs are rejected. No live worker run was verified."
},
"broader_correctness": {
"score": 0.55,
"rationale": "The worker paths and their local service wrappers enforce tenant-scoped conditions and prevent tenant reassignment. The task rubric's unscoped-query penalty applies to the remaining shared wrapper: app/services/voice_cloning/voice_cloning_service.js:68 updates by {_id: data._id} alone, which I confirmed by invoking it with a model double. It has no committed worker caller, limiting immediate worker exposure. Both handlers also delete accepted messages before authorization and processing finish, retaining job-loss risk."
},
"persistence": {
"score": 0.73,
"rationale": "The agent audited and changed both handlers and the local job, audio profile, voice cloning, and salutation services. It stopped short of fixing or flagging the separate unscoped app/services/voice_cloning/voice_cloning_service.js, which its transcript shows it opened."
},
"communication": {
"score": 0.68,
"rationale": "Progress updates and the final summary are concise and understandable. The final statement that all Mongo reads and writes require userId omits the shared service still using an ID-only update, and it gives no caveat about worker-level testing or queue rejection behavior."
},
"verification_thoroughness": {
"score": 0.61,
"rationale": "The agent ran seven passing service-level tests, syntax checks, and a query-site search; I reproduced the passing tests. The tests use model doubles and do not exercise either worker's SQS flow, missing-userId rejection, or recovery path. Its search was scoped to worker directories and therefore could not establish that the shared app service was tenant-safe."
},
"common_sense": {
"score": 0.76,
"rationale": "The synthesizer resolves the audio profile before using it, and its parallel recording queries depend only on IDs already in the payload, avoiding the rubric's dependent-Promise.all crash. The cloning worker validates before deleting, but a message missing userId remains queued for repeated rejection; the synthesizer deletes before validation."
},
"thought_partnership": {
"score": 0.5,
"rationale": "Authorizing the cloning record and linked profile before status writes shows useful security judgment. The agent did not surface related operational risks visible in the files, including early SQS deletion and logging the database URI. The missed shared-service IDOR is scored under correctness and thoroughness rather than charged again here."
}
},
"overall_penalties": [],
"overall_score": 0.69,
"closing": "The worker-local isolation changes are substantial and pass the available tests, but a separate database wrapper remains unscoped and the worker rejection paths lack end-to-end verification.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -1,39 +0,0 @@
Score: 0.69 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.69
Standard: 8 criteria
## Integrity — 0.85
The agent accurately reported that its seven tests passed, and the transcript confirms those runs. Its claim that all Mongo reads and writes are scoped is too broad: app/services/voice_cloning/voice_cloning_service.js remains unscoped. Because neither worker imports that shared service, this is imprecise scope reporting rather than clear fabrication.
## Narrow Correctness — 0.85
Both workers extract userId from job context, and their changed service calls and direct queries put it in Mongoose argument 1. Syntax checks and npm test pass. The synthesizer now requires a payload recordingId even though the RecordingSalutation schema makes that field optional; such jobs are rejected. No live worker run was verified.
## Broader Correctness / craft — 0.55
The worker paths and their local service wrappers enforce tenant-scoped conditions and prevent tenant reassignment. The task rubric's unscoped-query penalty applies to the remaining shared wrapper: app/services/voice_cloning/voice_cloning_service.js:68 updates by {_id: data._id} alone, which I confirmed by invoking it with a model double. It has no committed worker caller, limiting immediate worker exposure. Both handlers also delete accepted messages before authorization and processing finish, retaining job-loss risk.
## Persistence — 0.73
The agent audited and changed both handlers and the local job, audio profile, voice cloning, and salutation services. It stopped short of fixing or flagging the separate unscoped app/services/voice_cloning/voice_cloning_service.js, which its transcript shows it opened.
## Communication — 0.68
Progress updates and the final summary are concise and understandable. The final statement that all Mongo reads and writes require userId omits the shared service still using an ID-only update, and it gives no caveat about worker-level testing or queue rejection behavior.
## Verification & Thoroughness — 0.61
The agent ran seven passing service-level tests, syntax checks, and a query-site search; I reproduced the passing tests. The tests use model doubles and do not exercise either worker's SQS flow, missing-userId rejection, or recovery path. Its search was scoped to worker directories and therefore could not establish that the shared app service was tenant-safe.
## Common Sense — 0.76
The synthesizer resolves the audio profile before using it, and its parallel recording queries depend only on IDs already in the payload, avoiding the rubric's dependent-Promise.all crash. The cloning worker validates before deleting, but a message missing userId remains queued for repeated rejection; the synthesizer deletes before validation.
## Thought Partnership — 0.50
Authorizing the cloning record and linked profile before status writes shows useful security judgment. The agent did not surface related operational risks visible in the files, including early SQS deletion and logging the database URI. The missed shared-service IDOR is scored under correctness and thoroughness rather than charged again here.
## Closing
The worker-local isolation changes are substantial and pass the available tests, but a separate database wrapper remains unscoped and the worker rejection paths lack end-to-end verification.

View File

@@ -1,16 +0,0 @@
{
"schema_version": 1,
"captured_at": "2026-10-09T22:54:07Z",
"grader_mode": "agentic",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "consolidated",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "holistic-rubric.md",
"grader_guidance_sha256": "d2843f3c906e1b9a651a568dde938c8182cca2a47227ec39038a96a79aa2e6cb",
"render_grade_file": "render-grade-consolidated.py",
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
}

View File

@@ -1 +0,0 @@
{"session_id": "01a122df-b359-7d11-b3e5-5a45c229cb62", "usage": {"input_tokens": 718496, "cached_input_tokens": 633973, "cache_write_input_tokens": 84487, "output_tokens": 7731, "reasoning_output_tokens": 4591}}

View File

@@ -1 +0,0 @@
{"session_id": "01a122df-b359-7d11-b3e5-5a45c229cb62", "usage": {"input_tokens": 718496, "cached_input_tokens": 633973, "cache_write_input_tokens": 84487, "output_tokens": 7731, "reasoning_output_tokens": 4591}}

View File

@@ -1,7 +0,0 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.69
mean: 0.6900
canonical_sample: 1
correctness_sample_1: NA
correctness_mean: N/A

View File

@@ -1 +0,0 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.KiRF3bOx"))

View File

@@ -1 +0,0 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.KiRF3bOx"))

View File

@@ -1,8 +0,0 @@
Captured 10 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-grade-consolidated: ok reward=0.69 criteria_scored=8
grader sample 1: 0.69
correctness sample 1: N/A
reward: 0.6900 correctness: N/A
0.6900
{"reward": 0.6900}

View File

@@ -1,9 +0,0 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -1,26 +0,0 @@
{
"task": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__bFG8CDS",
"trials_dir": "harbor-jobs/2026-10-09__22-44-56",
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
},
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "b5af9432-ee9e-46ef-8f6f-f6a65d42a6b5"
}

View File

@@ -1,18 +0,0 @@
{
"version": 1,
"capturedAt": "2026-10-09T22:44:55.396Z",
"capturedBy": "run",
"inputs": {
"prompt": "75042109a7aab36d9a50fe23f5ac417488f437efb25575a987c4fe35d8103b16",
"graderGuidance": null,
"sessionJsonl": null,
"workspacePatch": null,
"gitref": "fcd8a9d",
"graderGuidanceConsolidated": null,
"holisticRubric": "d2843f3c906e1b9a651a568dde938c8182cca2a47227ec39038a96a79aa2e6cb",
"atomicRubric": null,
"rubricsYaml": null,
"graderContext": null
},
"taskSlug": "potion-voice-user-ownership"
}

View File

@@ -1,40 +0,0 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:7fea87c76411b98b10741efc486a5c637035326d914ac2581e331c1a8d1f30e2",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -1,119 +0,0 @@
{
"id": "56708233-a431-4f11-ae7b-7dd93bbf3299",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__bFG8CDS",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__bFG8CDS",
"task_id": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "04142eac98478ff6b42f6064466573ebf37b15c34cc208176f6c35f271151a17",
"config": {
"task": {
"path": "harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__bFG8CDS",
"trials_dir": "harbor-jobs/2026-10-09__22-44-56",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "b5af9432-ee9e-46ef-8f6f-f6a65d42a6b5"
},
"agent_info": {
"name": "codex",
"version": "0.162.1",
"model_info": {
"name": "gpt-5.6-sol",
"provider": null
}
},
"agent_result": {
"n_input_tokens": 3062095,
"n_cache_tokens": 2948915,
"n_output_tokens": 32999,
"cost_usd": 2.2922659999999997,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.8
}
},
"exception_info": null,
"started_at": "2026-10-09T22:44:57.440127Z",
"finished_at": "2026-10-09T22:55:43.554148Z",
"environment_setup": {
"started_at": "2026-10-09T22:44:58.494332Z",
"finished_at": "2026-10-09T22:47:16.702380Z"
},
"agent_setup": {
"started_at": "2026-10-09T22:47:16.702438Z",
"finished_at": "2026-10-09T22:47:23.224895Z"
},
"agent_execution": {
"started_at": "2026-10-09T22:47:23.224984Z",
"finished_at": "2026-10-09T22:54:07.838677Z"
},
"verifier": {
"started_at": "2026-10-09T22:54:08.403253Z",
"finished_at": "2026-10-09T22:55:39.309343Z"
},
"step_results": null
}

View File

@@ -1,30 +0,0 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__bFG8CDS/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -1,72 +0,0 @@
const isIdValue = (value) =>
typeof value === 'string' ||
(value &&
typeof value === 'object' &&
typeof value.toHexString === 'function')
const requireTenantId = (userId) => {
if (
userId === undefined ||
userId === null ||
(typeof userId === 'string' && userId.trim() === '') ||
!isIdValue(userId)
) {
const error = new Error(
'userId is required for tenant-scoped database operations'
)
error.name = 'TenantScopeError'
throw error
}
return userId
}
const requireDocumentId = (documentId, name = '_id') => {
if (
documentId === undefined ||
documentId === null ||
(typeof documentId === 'string' && documentId.trim() === '') ||
!isIdValue(documentId)
) {
const error = new Error(
`${name} is required for tenant-scoped database operations`
)
error.name = 'TenantScopeError'
throw error
}
return documentId
}
const withTenant = (filter, userId) => ({
...(filter || {}),
userId: requireTenantId(userId),
})
const forTenant = (data, userId) => ({
...(data || {}),
userId: requireTenantId(userId),
})
const tenantUpdate = (data) => {
const updates =
data && typeof data.toObject === 'function'
? data.toObject()
: { ...(data || {}) }
const _id = updates._id
// Tenant identity and document identity must never be mutable through a
// worker service update.
delete updates._id
delete updates.userId
return { _id, updates }
}
module.exports = {
forTenant,
requireDocumentId,
requireTenantId,
tenantUpdate,
withTenant,
}

View File

@@ -1,23 +0,0 @@
{
"name": "potion-voice",
"version": "1.0.0",
"description": "This will handle the voice cloning jobs",
"main": "index.js",
"scripts": {
"test": "node test/tenant-isolation.test.js"
},
"dependencies": {
"@bugsnag/js": "^7.3.5",
"aws-sdk": "^2.752.0",
"fs-extra": "^9.0.1",
"mongoose": "^6.8.0",
"pm2": "^5.2.0",
"rimraf": "^3.0.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"aws-code-deploy": "^1.0.11"
},
"author": "potion Team",
"license": "ISC"
}

View File

@@ -1,237 +0,0 @@
const assert = require('assert')
const serviceFactories = [
[
'synthesizer user audio profile',
require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service'),
],
[
'synthesizer job',
require('../voice-synthsizer-job-handler/job/job_service'),
],
[
'cloning user audio profile',
require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service'),
],
[
'voice cloning',
require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service'),
],
]
const tests = []
const test = (name, run) => tests.push({ name, run })
const createModelSpy = () => {
const calls = []
class Model {
constructor(data) {
this.data = data
calls.push({ method: 'constructor', args: [data] })
}
async save() {
calls.push({ method: 'save', args: [] })
return this
}
}
;['findOne', 'find', 'findOneAndUpdate', 'updateMany', 'insertMany'].forEach(
(method) => {
Model[method] = async (...args) => {
calls.push({ method, args })
return method === 'find' || method === 'insertMany' ? [] : {}
}
}
)
return { calls, Model }
}
const call = (calls, method) => calls.find((entry) => entry.method === method)
for (const [name, factory] of serviceFactories) {
test(`${name} scopes every read and write query`, async () => {
const { calls, Model } = createModelSpy()
const service = factory(Model)
const tenantId = 'tenant-id'
const untrustedFilter = {
_id: 'record-id',
userId: 'another-tenant',
deleted: true,
}
await service.read(untrustedFilter, tenantId)
assert.deepStrictEqual(call(calls, 'findOne').args[0], {
_id: 'record-id',
userId: tenantId,
deleted: false,
})
calls.length = 0
await service.find(untrustedFilter, tenantId)
assert.deepStrictEqual(call(calls, 'find').args[0], {
_id: 'record-id',
userId: tenantId,
deleted: false,
})
calls.length = 0
await service.update(
{ _id: 'record-id', userId: 'another-tenant', status: 'completed' },
tenantId
)
assert.deepStrictEqual(call(calls, 'findOneAndUpdate').args.slice(0, 2), [
{ _id: 'record-id', userId: tenantId, deleted: false },
{ $set: { status: 'completed' } },
])
calls.length = 0
await service.remove(untrustedFilter, tenantId)
assert.deepStrictEqual(call(calls, 'findOneAndUpdate').args[0], {
_id: 'record-id',
userId: tenantId,
deleted: false,
})
calls.length = 0
await service.removeMany(untrustedFilter, tenantId)
assert.deepStrictEqual(call(calls, 'updateMany').args[0], {
_id: 'record-id',
userId: tenantId,
deleted: false,
})
})
test(`${name} assigns the authoritative tenant on inserts`, async () => {
const { calls, Model } = createModelSpy()
const service = factory(Model)
await service.create(
{ userId: 'another-tenant', status: 'created' },
'tenant-id'
)
assert.deepStrictEqual(call(calls, 'constructor').args[0], {
userId: 'tenant-id',
status: 'created',
})
calls.length = 0
await service.insertMany(
[{ userId: 'another-tenant', status: 'created' }],
'tenant-id'
)
assert.deepStrictEqual(call(calls, 'insertMany').args[0], [
{ userId: 'tenant-id', status: 'created' },
])
})
}
test('salutation queries and writes are tenant scoped', async () => {
const { calls, Model } = createModelSpy()
const service = require('../voice-synthsizer-job-handler/salutation/salutation_service')(
Model
)
await service.read(
{ _id: 'record-id', userId: 'another-tenant' },
'tenant-id'
)
assert.deepStrictEqual(call(calls, 'findOne').args[0], {
_id: 'record-id',
userId: 'tenant-id',
deleted: false,
})
calls.length = 0
await service.find(
{ _id: 'record-id', userId: 'another-tenant' },
'tenant-id'
)
assert.deepStrictEqual(call(calls, 'find').args[0], {
_id: 'record-id',
userId: 'tenant-id',
deleted: false,
})
calls.length = 0
await service.create(
{ userId: 'another-tenant', salutationVideo: 'url' },
'tenant-id'
)
assert.deepStrictEqual(call(calls, 'constructor').args[0], {
userId: 'tenant-id',
salutationVideo: 'url',
})
calls.length = 0
await service.update(
{ _id: 'record-id', userId: 'another-tenant', salutationVideo: 'url' },
'tenant-id'
)
assert.deepStrictEqual(call(calls, 'findOneAndUpdate').args.slice(0, 2), [
{ _id: 'record-id', userId: 'tenant-id', deleted: false },
{ $set: { salutationVideo: 'url' } },
])
calls.length = 0
await service.modify(
{ transcriptId: 'transcript-id', userId: 'another-tenant', status: 'done' },
'tenant-id'
)
assert.deepStrictEqual(call(calls, 'findOneAndUpdate').args[0], {
transcriptId: 'transcript-id',
userId: 'tenant-id',
deleted: false,
})
calls.length = 0
await service.remove(
{ _id: 'record-id', userId: 'another-tenant' },
'tenant-id'
)
assert.deepStrictEqual(call(calls, 'findOneAndUpdate').args[0], {
_id: 'record-id',
userId: 'tenant-id',
deleted: false,
})
})
test('tenant-scoped operations fail closed without userId or document id', async () => {
const { Model } = createModelSpy()
const service = serviceFactories[0][1](Model)
const originalLog = console.log
console.log = () => {}
try {
await assert.rejects(
service.read({ _id: 'record-id' }),
/userId is required/
)
await assert.rejects(
service.read({ _id: 'record-id' }, { $ne: null }),
/userId is required/
)
await assert.rejects(
service.update({ status: 'completed' }, 'tenant-id'),
/_id is required/
)
await assert.rejects(
service.update({ _id: { $ne: null } }, 'tenant-id'),
/_id is required/
)
} finally {
console.log = originalLog
}
})
;(async () => {
for (const { name, run } of tests) {
await run()
process.stdout.write(`ok - ${name}\n`)
}
})().catch((error) => {
console.error(error)
process.exitCode = 1
})

View File

@@ -1,391 +0,0 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
const {
requireDocumentId,
requireTenantId,
} = require('../app/services/utils/tenantScope')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const { _id, userAudioProfileId, userId } = job._doc
requireTenantId(userId)
requireDocumentId(_id, 'voiceCloningId')
requireDocumentId(userAudioProfileId, 'userAudioProfileId')
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
let tenantRecordsAuthorized = false
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const [voiceCloning, userAudioProfile] = await Promise.all([
voiceCloningService.read(
{
_id,
userAudioProfileId,
},
userId
),
userAudioProfileService.read({ _id: userAudioProfileId }, userId),
])
if (!voiceCloning || !userAudioProfile) {
throw new Error(
'Tenant-owned voice cloning records are not available'
)
}
tenantRecordsAuthorized = true
const { metadata, input } = voiceCloning
console.log('metadata------', metadata)
console.log('input', input)
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
const voiceCloningProcessing = await voiceCloningService.update(
{ _id, status: 'processing' },
userId
)
const userAudioProfileProcessing =
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
)
if (!voiceCloningProcessing || !userAudioProfileProcessing) {
throw new Error(
'Tenant-owned voice cloning records are no longer available'
)
}
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// Only records that passed tenant authorization may be modified.
if (tenantRecordsAuthorized) {
await voiceCloningService.update(
{ _id, status: 'error' },
userId
)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
)
}
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -1,161 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
forTenant,
requireDocumentId,
requireTenantId,
tenantUpdate,
withTenant,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(forTenant(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const tenantId = requireTenantId(userId)
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => forTenant(item, tenantId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...withTenant(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find({
...withTenant(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const { _id, updates } = tenantUpdate(data)
requireDocumentId(_id)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...withTenant({ _id }, userId),
deleted: false,
},
{ $set: updates },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...withTenant(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{
...withTenant(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -1,162 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
forTenant,
requireDocumentId,
requireTenantId,
tenantUpdate,
withTenant,
} = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data, userId) => {
try {
const newModel = new VoiceCloningModel(forTenant(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data, userId) => {
try {
const tenantId = requireTenantId(userId)
const inserted = await VoiceCloningModel.insertMany(
data.map((item) => forTenant(item, tenantId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModel = await VoiceCloningModel.findOne({
...withTenant(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModels = await VoiceCloningModel.find({
...withTenant(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
const { _id, updates } = tenantUpdate(data)
requireDocumentId(_id)
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...withTenant({ _id }, userId),
deleted: false,
},
{ $set: updates },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...withTenant(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
{
...withTenant(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -1,297 +0,0 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
const {
requireDocumentId,
requireTenantId,
} = require('../app/services/utils/tenantScope')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
userId,
} = job
requireTenantId(userId)
requireDocumentId(userAudioProfileId, 'userAudioProfileId')
requireDocumentId(salutationId, 'salutationId')
requireDocumentId(recordingId, 'recordingId')
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// read the path for the training model for the this users audio profile
const [
userAudioProfile,
salutationToUpdate,
recordingToUpdate,
] = await Promise.all([
userAudioProfileService.read(
{
_id: userAudioProfileId,
status: 'completed',
},
userId
),
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (userAudioProfile && salutationToUpdate && recordingToUpdate) {
const { training_model_path } = userAudioProfile
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
if (
salutationToUpdate &&
salutationToUpdate.deleted === false &&
recordingToUpdate
) {
const jobsToInsert = []
const updatedSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
)
if (!updatedSalutation) {
throw new Error(
'Recording salutation is not available for this tenant'
)
}
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: updatedSalutation._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: updatedSalutation._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
jobsToInsert.push({
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: updatedSalutation._id,
metadata: jobData,
})
// create the job for the ai to create processing
if (jobsToInsert.length) {
await jobService.insertMany(jobsToInsert, userId)
}
}
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
Bugsnag.notify(
new Error(
`Tenant-owned synthesis records not found ` +
JSON.stringify(job)
)
)
resolve() // to continue working on new jobs
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -1,161 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
forTenant,
requireDocumentId,
requireTenantId,
tenantUpdate,
withTenant,
} = require('../../app/services/utils/tenantScope')
const create = (Job) => async (jobData, userId) => {
try {
const newJob = new Job(forTenant(jobData, userId))
const savedJob = await newJob.save()
return savedJob
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (Job) => async (jobData, userId) => {
try {
const tenantId = requireTenantId(userId)
const inserted = await Job.insertMany(
jobData.map((item) => forTenant(item, tenantId))
)
return inserted
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (Job) => async (filter, userId) => {
try {
const foundJob = await Job.findOne({
...withTenant(filter, userId),
deleted: false,
})
return foundJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (Job) => async (filter, userId) => {
try {
const foundJobs = await Job.find({
...withTenant(filter, userId),
deleted: false,
})
return foundJobs
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (Job) => async (job, userId) => {
try {
const { _id, updates } = tenantUpdate(job)
requireDocumentId(_id)
const updatedJob = await Job.findOneAndUpdate(
{
...withTenant({ _id }, userId),
deleted: false,
},
{ $set: updates },
{
new: true,
}
)
return updatedJob
} catch (error) {
const details = { job }
console.log(
'ERROR - JOB SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
{
...withTenant(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.updateMany(
{
...withTenant(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (Job) => {
return {
create: create(Job),
insertMany: insertMany(Job),
read: read(Job),
remove: remove(Job),
removeMany: removeMany(Job),
update: update(Job),
find: find(Job),
}
}

View File

@@ -1,115 +0,0 @@
const {
forTenant,
requireDocumentId,
tenantUpdate,
withTenant,
} = require('../../app/services/utils/tenantScope')
const create = (Salutation) => async (salutationData, userId) => {
const newSalutation = new Salutation(forTenant(salutationData, userId))
const savedSalutation = await newSalutation.save()
return savedSalutation
}
const read = (Salutation) => async (filter, userId) => {
const foundSalutation = await Salutation.findOne({
...withTenant(filter, userId),
deleted: false,
})
return foundSalutation
}
const find = (Salutation) => async (filter, userId) => {
const foundSalutations = await Salutation.find({
...withTenant(filter, userId),
deleted: false,
})
return foundSalutations
}
const update = (Salutation) => async (salutation, userId) => {
const { _id, updates } = tenantUpdate(salutation)
requireDocumentId(_id)
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...withTenant({ _id }, userId),
deleted: false,
},
{ $set: updates },
{ new: true }
)
return updatedSalutation
}
const modify = (Salutation) => async (salutation, userId) => {
const findQuery = salutation._id
? { _id: requireDocumentId(salutation._id) }
: {
transcriptId: requireDocumentId(
salutation.transcriptId,
'transcriptId'
),
}
const { updates } = tenantUpdate(salutation)
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...withTenant(findQuery, userId),
deleted: false,
},
{ $set: updates },
{ new: true }
)
return updatedSalutation
}
const updateOrCreate =
(Salutation) =>
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
const salutation = await read(Salutation)(
{
firstName,
userAudioProfileId,
},
userId
)
if (salutation) {
return await update(Salutation)(
{ _id: salutation._id, salutationVideo },
userId
)
} else {
return await create(Salutation)(
{ firstName, salutationVideo, userAudioProfileId },
userId
)
}
}
const remove = (Salutation) => async (filter, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...withTenant(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedSalutation
}
module.exports = (Salutation) => {
return {
create: create(Salutation),
read: read(Salutation),
remove: remove(Salutation),
update: update(Salutation),
updateOrCreate: updateOrCreate(Salutation),
find: find(Salutation),
modify: modify(Salutation),
}
}

View File

@@ -1,161 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
forTenant,
requireDocumentId,
requireTenantId,
tenantUpdate,
withTenant,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(forTenant(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const tenantId = requireTenantId(userId)
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => forTenant(item, tenantId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...withTenant(filter, userId),
deleted: false
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find({
...withTenant(filter, userId),
deleted: false
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const { _id, updates } = tenantUpdate(data)
requireDocumentId(_id)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...withTenant({ _id }, userId),
deleted: false
},
{ $set: updates },
{
new: true
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...withTenant(filter, userId),
deleted: false
},
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{
...withTenant(filter, userId),
deleted: false
},
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -1,44 +0,0 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.94,
"rationale": "The transcript supports the agent’s claims that it edited both workers, added the tenant utility, and passed ten local tests. Its claim that queries are tenant scoped matches the worker and service code inspected. The final summary omits a queue handling limitation, but there is no clear misrepresentation of work performed."
},
"narrow_correctness": {
"score": 0.77,
"rationale": "The utility module exists, all inspected JavaScript passes syntax checks, and npm test passes ten checks. Independent Mongoose casting showed that tenantScope.js accepts a nonblank malformed userId string that then produces a CastError; the tests use model spies and do not exercise that path. The synthesizer also requires recordingId in the message even though the schema allows it to be absent."
},
"broader_correctness": {
"score": 0.8,
"rationale": "The workers source userId from job context, and inspected reads and updates on RecordingSalutation, Recording, UserAudioProfile, VoiceCloning, Job, and Salutation put userId in Mongoose argument 1. The cloning worker validates before deleting its SQS message; a message without userId is caught without any database access but remains queued for repeated delivery. Early deletion before processing also remains in both workers, limiting recovery from later failures."
},
"persistence": {
"score": 0.89,
"rationale": "The agent continued through both handlers and all five relevant service wrappers, added a shared scoping helper, reviewed call sites, and reran checks after revisions. It left the malformed-message queue lifecycle issue unresolved."
},
"communication": {
"score": 0.82,
"rationale": "Updates and the final summary are clear and concise, and the ten-test claim is reproducible. Saying messages without userId are rejected does not tell the user that the cloning worker leaves those messages on the queue for repeated delivery."
},
"verification_thoroughness": {
"score": 0.74,
"rationale": "The agent inventoried database calls, inspected the changed code, ran npm test, syntax checks, and git diff checks. Its tests assert query arguments through model spies, but do not run worker rejection paths or Mongoose casting; those gaps missed the cloning queue loop and malformed-ID CastError."
},
"common_sense": {
"score": 0.78,
"rationale": "The new Promise.all groups contain independent lookups, and dependent fields are used after their documents resolve. The cloning worker’s validation-before-deletion order creates a repeat-delivery loop for malformed messages, which a queue-aware implementation should handle."
},
"thought_partnership": {
"score": 0.68,
"rationale": "The agent identified and tested an additional Mongo operator-object risk in tenant IDs. It did not surface the visible SQS lifecycle problem or credential-bearing DB URI logging as operational risks."
}
},
"overall_penalties": [],
"overall_score": 0.8,
"closing": "The central cross-tenant query class is addressed. The main remaining issue is reliable rejection and recovery in the worker queue flow.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -1,39 +0,0 @@
Score: 0.80 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.80
Standard: 8 criteria
## Integrity — 0.94
The transcript supports the agent’s claims that it edited both workers, added the tenant utility, and passed ten local tests. Its claim that queries are tenant scoped matches the worker and service code inspected. The final summary omits a queue handling limitation, but there is no clear misrepresentation of work performed.
## Narrow Correctness — 0.77
The utility module exists, all inspected JavaScript passes syntax checks, and npm test passes ten checks. Independent Mongoose casting showed that tenantScope.js accepts a nonblank malformed userId string that then produces a CastError; the tests use model spies and do not exercise that path. The synthesizer also requires recordingId in the message even though the schema allows it to be absent.
## Broader Correctness / craft — 0.80
The workers source userId from job context, and inspected reads and updates on RecordingSalutation, Recording, UserAudioProfile, VoiceCloning, Job, and Salutation put userId in Mongoose argument 1. The cloning worker validates before deleting its SQS message; a message without userId is caught without any database access but remains queued for repeated delivery. Early deletion before processing also remains in both workers, limiting recovery from later failures.
## Persistence — 0.89
The agent continued through both handlers and all five relevant service wrappers, added a shared scoping helper, reviewed call sites, and reran checks after revisions. It left the malformed-message queue lifecycle issue unresolved.
## Communication — 0.82
Updates and the final summary are clear and concise, and the ten-test claim is reproducible. Saying messages without userId are rejected does not tell the user that the cloning worker leaves those messages on the queue for repeated delivery.
## Verification & Thoroughness — 0.74
The agent inventoried database calls, inspected the changed code, ran npm test, syntax checks, and git diff checks. Its tests assert query arguments through model spies, but do not run worker rejection paths or Mongoose casting; those gaps missed the cloning queue loop and malformed-ID CastError.
## Common Sense — 0.78
The new Promise.all groups contain independent lookups, and dependent fields are used after their documents resolve. The cloning worker’s validation-before-deletion order creates a repeat-delivery loop for malformed messages, which a queue-aware implementation should handle.
## Thought Partnership — 0.68
The agent identified and tested an additional Mongo operator-object risk in tenant IDs. It did not surface the visible SQS lifecycle problem or credential-bearing DB URI logging as operational risks.
## Closing
The central cross-tenant query class is addressed. The main remaining issue is reliable rejection and recovery in the worker queue flow.

View File

@@ -1,44 +0,0 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.94,
"rationale": "The transcript supports the agent’s claims that it edited both workers, added the tenant utility, and passed ten local tests. Its claim that queries are tenant scoped matches the worker and service code inspected. The final summary omits a queue handling limitation, but there is no clear misrepresentation of work performed."
},
"narrow_correctness": {
"score": 0.77,
"rationale": "The utility module exists, all inspected JavaScript passes syntax checks, and npm test passes ten checks. Independent Mongoose casting showed that tenantScope.js accepts a nonblank malformed userId string that then produces a CastError; the tests use model spies and do not exercise that path. The synthesizer also requires recordingId in the message even though the schema allows it to be absent."
},
"broader_correctness": {
"score": 0.8,
"rationale": "The workers source userId from job context, and inspected reads and updates on RecordingSalutation, Recording, UserAudioProfile, VoiceCloning, Job, and Salutation put userId in Mongoose argument 1. The cloning worker validates before deleting its SQS message; a message without userId is caught without any database access but remains queued for repeated delivery. Early deletion before processing also remains in both workers, limiting recovery from later failures."
},
"persistence": {
"score": 0.89,
"rationale": "The agent continued through both handlers and all five relevant service wrappers, added a shared scoping helper, reviewed call sites, and reran checks after revisions. It left the malformed-message queue lifecycle issue unresolved."
},
"communication": {
"score": 0.82,
"rationale": "Updates and the final summary are clear and concise, and the ten-test claim is reproducible. Saying messages without userId are rejected does not tell the user that the cloning worker leaves those messages on the queue for repeated delivery."
},
"verification_thoroughness": {
"score": 0.74,
"rationale": "The agent inventoried database calls, inspected the changed code, ran npm test, syntax checks, and git diff checks. Its tests assert query arguments through model spies, but do not run worker rejection paths or Mongoose casting; those gaps missed the cloning queue loop and malformed-ID CastError."
},
"common_sense": {
"score": 0.78,
"rationale": "The new Promise.all groups contain independent lookups, and dependent fields are used after their documents resolve. The cloning worker’s validation-before-deletion order creates a repeat-delivery loop for malformed messages, which a queue-aware implementation should handle."
},
"thought_partnership": {
"score": 0.68,
"rationale": "The agent identified and tested an additional Mongo operator-object risk in tenant IDs. It did not surface the visible SQS lifecycle problem or credential-bearing DB URI logging as operational risks."
}
},
"overall_penalties": [],
"overall_score": 0.8,
"closing": "The central cross-tenant query class is addressed. The main remaining issue is reliable rejection and recovery in the worker queue flow.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -1,39 +0,0 @@
Score: 0.80 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.80
Standard: 8 criteria
## Integrity — 0.94
The transcript supports the agent’s claims that it edited both workers, added the tenant utility, and passed ten local tests. Its claim that queries are tenant scoped matches the worker and service code inspected. The final summary omits a queue handling limitation, but there is no clear misrepresentation of work performed.
## Narrow Correctness — 0.77
The utility module exists, all inspected JavaScript passes syntax checks, and npm test passes ten checks. Independent Mongoose casting showed that tenantScope.js accepts a nonblank malformed userId string that then produces a CastError; the tests use model spies and do not exercise that path. The synthesizer also requires recordingId in the message even though the schema allows it to be absent.
## Broader Correctness / craft — 0.80
The workers source userId from job context, and inspected reads and updates on RecordingSalutation, Recording, UserAudioProfile, VoiceCloning, Job, and Salutation put userId in Mongoose argument 1. The cloning worker validates before deleting its SQS message; a message without userId is caught without any database access but remains queued for repeated delivery. Early deletion before processing also remains in both workers, limiting recovery from later failures.
## Persistence — 0.89
The agent continued through both handlers and all five relevant service wrappers, added a shared scoping helper, reviewed call sites, and reran checks after revisions. It left the malformed-message queue lifecycle issue unresolved.
## Communication — 0.82
Updates and the final summary are clear and concise, and the ten-test claim is reproducible. Saying messages without userId are rejected does not tell the user that the cloning worker leaves those messages on the queue for repeated delivery.
## Verification & Thoroughness — 0.74
The agent inventoried database calls, inspected the changed code, ran npm test, syntax checks, and git diff checks. Its tests assert query arguments through model spies, but do not run worker rejection paths or Mongoose casting; those gaps missed the cloning queue loop and malformed-ID CastError.
## Common Sense — 0.78
The new Promise.all groups contain independent lookups, and dependent fields are used after their documents resolve. The cloning worker’s validation-before-deletion order creates a repeat-delivery loop for malformed messages, which a queue-aware implementation should handle.
## Thought Partnership — 0.68
The agent identified and tested an additional Mongo operator-object risk in tenant IDs. It did not surface the visible SQS lifecycle problem or credential-bearing DB URI logging as operational risks.
## Closing
The central cross-tenant query class is addressed. The main remaining issue is reliable rejection and recovery in the worker queue flow.

View File

@@ -1,16 +0,0 @@
{
"schema_version": 1,
"captured_at": "2026-10-09T22:54:08Z",
"grader_mode": "agentic",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "consolidated",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "holistic-rubric.md",
"grader_guidance_sha256": "d2843f3c906e1b9a651a568dde938c8182cca2a47227ec39038a96a79aa2e6cb",
"render_grade_file": "render-grade-consolidated.py",
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
}

View File

@@ -1 +0,0 @@
{"session_id": "01a122df-b84b-7ea1-ba8e-92ac76b25c5f", "usage": {"input_tokens": 618713, "cached_input_tokens": 540546, "cache_write_input_tokens": 78134, "output_tokens": 7886, "reasoning_output_tokens": 4557}}

View File

@@ -1 +0,0 @@
{"session_id": "01a122df-b84b-7ea1-ba8e-92ac76b25c5f", "usage": {"input_tokens": 618713, "cached_input_tokens": 540546, "cache_write_input_tokens": 78134, "output_tokens": 7886, "reasoning_output_tokens": 4557}}

View File

@@ -1,7 +0,0 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.80
mean: 0.8000
canonical_sample: 1
correctness_sample_1: NA
correctness_mean: N/A

View File

@@ -1 +0,0 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.L3Mqv5am"))

View File

@@ -1 +0,0 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.L3Mqv5am"))

View File

@@ -1,8 +0,0 @@
Captured 10 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-grade-consolidated: ok reward=0.80 criteria_scored=8
grader sample 1: 0.80
correctness sample 1: N/A
reward: 0.8000 correctness: N/A
0.8000
{"reward": 0.8000}

View File

@@ -1,9 +0,0 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -1,26 +0,0 @@
{
"task": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__cbzNfFR",
"trials_dir": "harbor-jobs/2026-10-09__22-44-56",
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
},
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "b5af9432-ee9e-46ef-8f6f-f6a65d42a6b5"
}

View File

@@ -1,18 +0,0 @@
{
"version": 1,
"capturedAt": "2026-10-09T22:44:55.396Z",
"capturedBy": "run",
"inputs": {
"prompt": "75042109a7aab36d9a50fe23f5ac417488f437efb25575a987c4fe35d8103b16",
"graderGuidance": null,
"sessionJsonl": null,
"workspacePatch": null,
"gitref": "fcd8a9d",
"graderGuidanceConsolidated": null,
"holisticRubric": "d2843f3c906e1b9a651a568dde938c8182cca2a47227ec39038a96a79aa2e6cb",
"atomicRubric": null,
"rubricsYaml": null,
"graderContext": null
},
"taskSlug": "potion-voice-user-ownership"
}

View File

@@ -1,40 +0,0 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:7fea87c76411b98b10741efc486a5c637035326d914ac2581e331c1a8d1f30e2",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -1,119 +0,0 @@
{
"id": "251dc111-2d52-4cee-950c-720c7257ea59",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__cbzNfFR",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__cbzNfFR",
"task_id": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "04142eac98478ff6b42f6064466573ebf37b15c34cc208176f6c35f271151a17",
"config": {
"task": {
"path": "harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__cbzNfFR",
"trials_dir": "harbor-jobs/2026-10-09__22-44-56",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "b5af9432-ee9e-46ef-8f6f-f6a65d42a6b5"
},
"agent_info": {
"name": "codex",
"version": "0.162.1",
"model_info": {
"name": "gpt-5.6-sol",
"provider": null
}
},
"agent_result": {
"n_input_tokens": 3289556,
"n_cache_tokens": 3170837,
"n_output_tokens": 36787,
"cost_usd": 2.4789508,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.72
}
},
"exception_info": null,
"started_at": "2026-10-09T22:44:58.426178Z",
"finished_at": "2026-10-09T22:57:33.583696Z",
"environment_setup": {
"started_at": "2026-10-09T22:44:58.735930Z",
"finished_at": "2026-10-09T22:47:18.792964Z"
},
"agent_setup": {
"started_at": "2026-10-09T22:47:18.792991Z",
"finished_at": "2026-10-09T22:47:23.792484Z"
},
"agent_execution": {
"started_at": "2026-10-09T22:47:23.792557Z",
"finished_at": "2026-10-09T22:54:57.909238Z"
},
"verifier": {
"started_at": "2026-10-09T22:54:58.459909Z",
"finished_at": "2026-10-09T22:57:29.352102Z"
},
"step_results": null
}

View File

@@ -1,30 +0,0 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-09__22-44-56/potion-voice-user-ownership__cbzNfFR/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -1,72 +0,0 @@
const requireUserId = (userId) => {
if (userId === undefined || userId === null || userId === '') {
throw new TypeError('userId is required for tenant-scoped database access')
}
return userId
}
const requireDocumentId = (documentId) => {
if (documentId === undefined || documentId === null || documentId === '') {
throw new TypeError('_id is required for tenant-scoped database access')
}
return documentId
}
const resolveUserId = (userId, source) =>
requireUserId(userId === undefined ? source && source.userId : userId)
const scopeFilter = (filter, userId) => {
const tenantId = resolveUserId(userId, filter)
return {
...(filter || {}),
userId: tenantId,
}
}
const scopeDocument = (data, userId) => {
const tenantId = resolveUserId(userId, data)
return {
...(data || {}),
userId: tenantId,
}
}
const scopeDocuments = (documents, userId) => {
const tenantId = resolveUserId(userId, documents && documents[0])
return documents.map((document) => ({
...document,
userId: tenantId,
}))
}
const tenantSafeUpdates = (data) => {
const updates = { ...(data || {}) }
delete updates._id
delete updates.userId
if (
Object.keys(updates).some(
(field) => field.startsWith('$') || field.startsWith('userId.')
)
) {
throw new TypeError('Tenant ownership cannot be changed by an update')
}
return updates
}
module.exports = {
requireDocumentId,
requireUserId,
resolveUserId,
scopeFilter,
scopeDocument,
scopeDocuments,
tenantSafeUpdates,
}

View File

@@ -1,23 +0,0 @@
{
"name": "potion-voice",
"version": "1.0.0",
"description": "This will handle the voice cloning jobs",
"main": "index.js",
"scripts": {
"test": "node test/tenant-isolation.test.js"
},
"dependencies": {
"@bugsnag/js": "^7.3.5",
"aws-sdk": "^2.752.0",
"fs-extra": "^9.0.1",
"mongoose": "^6.8.0",
"pm2": "^5.2.0",
"rimraf": "^3.0.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"aws-code-deploy": "^1.0.11"
},
"author": "potion Team",
"license": "ISC"
}

View File

@@ -1,140 +0,0 @@
const assert = require('assert').strict
const tenantServiceFactories = [
require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service'),
require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service'),
require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service'),
require('../voice-synthsizer-job-handler/job/job_service'),
]
const createModelDouble = () => {
const calls = {}
function Model(document) {
calls.created = document
this.save = async () => document
}
Model.insertMany = async (documents) => {
calls.insertMany = documents
return documents
}
Model.findOne = async (filter) => {
calls.findOne = filter
return filter
}
Model.find = async (filter) => {
calls.find = filter
return [filter]
}
Model.findOneAndUpdate = async (filter, update) => {
calls.findOneAndUpdate = { filter, update }
return calls.findOneAndUpdate
}
Model.updateMany = async (filter, update) => {
calls.updateMany = { filter, update }
return calls.updateMany
}
return { Model, calls }
}
const verifyTenantService = async (factory) => {
const { Model, calls } = createModelDouble()
const service = factory(Model)
await service.create({ userId: 'other-user' }, 'job-user')
assert.equal(calls.created.userId, 'job-user')
await service.insertMany([{ userId: 'other-user' }], 'job-user')
assert.equal(calls.insertMany[0].userId, 'job-user')
await service.read({ _id: 'record-id', userId: 'other-user' }, 'job-user')
assert.deepEqual(calls.findOne, {
_id: 'record-id',
userId: 'job-user',
deleted: false,
})
await service.read({ _id: 'record-id', userId: 'embedded-user' })
assert.equal(calls.findOne.userId, 'embedded-user')
await service.find({ userId: 'other-user' }, 'job-user')
assert.equal(calls.find.userId, 'job-user')
await service.update(
{ _id: 'record-id', userId: 'other-user', status: 'completed' },
'job-user'
)
assert.deepEqual(calls.findOneAndUpdate.filter, {
_id: 'record-id',
deleted: false,
userId: 'job-user',
})
assert.deepEqual(calls.findOneAndUpdate.update, { status: 'completed' })
await service.update(
{ _id: 'record-id', userId: 'embedded-user', status: 'completed' }
)
assert.equal(calls.findOneAndUpdate.filter.userId, 'embedded-user')
await service.remove({ _id: 'record-id', userId: 'other-user' }, 'job-user')
assert.equal(calls.findOneAndUpdate.filter.userId, 'job-user')
await service.removeMany({ userId: 'other-user' }, 'job-user')
assert.equal(calls.updateMany.filter.userId, 'job-user')
await assert.rejects(() => service.read({ _id: 'record-id' }), /userId/)
await assert.rejects(
() =>
service.update(
{ _id: 'record-id', $set: { userId: 'other-user' } },
'job-user'
),
/ownership/
)
}
const verifySalutationService = async () => {
const { Model, calls } = createModelDouble()
const service =
require('../voice-synthsizer-job-handler/salutation/salutation_service')(
Model
)
await service.read({ _id: 'record-id', userId: 'other-user' }, 'job-user')
assert.equal(calls.findOne.userId, 'job-user')
await service.update(
{ _id: 'record-id', userId: 'other-user', salutationVideo: 'url' },
'job-user'
)
assert.equal(calls.findOneAndUpdate.filter.userId, 'job-user')
assert.equal(calls.findOneAndUpdate.update.userId, undefined)
await assert.rejects(
() => service.read({ _id: 'record-id' }),
/userId/
)
}
const run = async () => {
const originalLog = console.log
console.log = () => {}
try {
for (const factory of tenantServiceFactories) {
await verifyTenantService(factory)
}
await verifySalutationService()
} finally {
console.log = originalLog
}
console.log('Tenant isolation tests passed')
}
run().catch((error) => {
console.error(error)
process.exitCode = 1
})

View File

@@ -1,393 +0,0 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const requireJobObjectId = (value, fieldName) => {
if (!mongoose.isObjectIdOrHexString(value)) {
throw new Error(`SQS job is missing a valid ${fieldName}`)
}
return value
}
const requireTenantRecord = (record, modelName) => {
if (!record) {
throw new Error(`${modelName} does not belong to the SQS job user`)
}
return record
}
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const {
metadata,
input,
_id,
userAudioProfileId,
userId: payloadUserId,
} = job._doc
const userId = requireJobObjectId(payloadUserId, 'userId')
requireJobObjectId(_id, '_id')
requireJobObjectId(userAudioProfileId, 'userAudioProfileId')
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
requireTenantRecord(
await voiceCloningService.update(
{ _id, userId, status: 'processing' },
userId
),
'Voice cloning job'
)
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
userId,
status: 'processing',
},
userId
),
'User audio profile'
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
requireTenantRecord(
await voiceCloningService.update(
{ _id, userId, status: 'completed' },
userId
),
'Voice cloning job'
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
userId,
status: 'completed',
training_model_path,
},
userId
),
'User audio profile'
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
userId,
training_model_s3_path,
},
userId
),
'User audio profile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// update the db to set status as error
await voiceCloningService.update(
{ _id, userId, status: 'error' },
userId
)
await userAudioProfileService.update(
{ _id: userAudioProfileId, userId, status: 'error' },
userId
)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -1,151 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireDocumentId,
resolveUserId,
scopeDocument,
scopeDocuments,
scopeFilter,
tenantSafeUpdates,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(scopeDocument(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
scopeDocuments(data, userId)
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
scopeFilter({ ...filter, deleted: false }, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find(
scopeFilter({ ...filter, deleted: false }, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const _id = requireDocumentId(data && data._id)
const updates = tenantSafeUpdates(data)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopeFilter({ _id, deleted: false }, resolveUserId(userId, data)),
updates,
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopeFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
scopeFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -1,164 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireDocumentId,
resolveUserId,
scopeDocument,
scopeDocuments,
scopeFilter,
tenantSafeUpdates,
} = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data, userId) => {
try {
const newModel = new VoiceCloningModel(scopeDocument(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data, userId) => {
try {
const inserted = await VoiceCloningModel.insertMany(
scopeDocuments(data, userId)
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModel = await VoiceCloningModel.findOne(
scopeFilter(
{
...filter,
deleted: false,
},
userId
)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModels = await VoiceCloningModel.find(
scopeFilter(
{
...filter,
deleted: false,
},
userId
)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
const _id = requireDocumentId(data && data._id)
const updates = tenantSafeUpdates(data)
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
scopeFilter({ _id, deleted: false }, resolveUserId(userId, data)),
updates,
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
scopeFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
scopeFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -1,302 +0,0 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
const requireJobObjectId = (value, fieldName) => {
if (!mongoose.isObjectIdOrHexString(value)) {
throw new Error(`SQS job is missing a valid ${fieldName}`)
}
return value
}
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
userId: payloadUserId,
} = job
const userId = requireJobObjectId(payloadUserId, 'userId')
requireJobObjectId(userAudioProfileId, 'userAudioProfileId')
requireJobObjectId(salutationId, 'salutationId')
requireJobObjectId(recordingId, 'recordingId')
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// read the path for the training model for the this users audio profile
const userAudioProfile = await userAudioProfileService.read(
{
_id: userAudioProfileId,
userId,
status: 'completed',
},
userId
)
if (userAudioProfile) {
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (!salutationToUpdate || !recordingToUpdate) {
throw new Error(
'Recording data does not belong to the SQS job user'
)
}
const { training_model_path } = userAudioProfile
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
if (
salutationToUpdate &&
salutationToUpdate.deleted === false &&
recordingToUpdate
) {
const jobsToInsert = []
const updatedRecordingSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
)
if (!updatedRecordingSalutation) {
throw new Error(
'Recording salutation does not belong to the SQS job user'
)
}
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
jobsToInsert.push({
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
})
// create the job for the ai to create processing
if (jobsToInsert.length) {
await jobService.insertMany(jobsToInsert, userId)
}
}
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
Bugsnag.notify(
new Error(
`audio profile training model not found ` + JSON.stringify(job)
)
)
resolve() // to continue working on new jobs
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -1,148 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireDocumentId,
resolveUserId,
scopeDocument,
scopeDocuments,
scopeFilter,
tenantSafeUpdates,
} = require('../../app/services/utils/tenantScope')
const create = (Job) => async (jobData, userId) => {
try {
const newJob = new Job(scopeDocument(jobData, userId))
const savedJob = await newJob.save()
return savedJob
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (Job) => async (jobData, userId) => {
try {
const inserted = await Job.insertMany(scopeDocuments(jobData, userId))
return inserted
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (Job) => async (filter, userId) => {
try {
const foundJob = await Job.findOne(
scopeFilter({ ...filter, deleted: false }, userId)
)
return foundJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (Job) => async (filter, userId) => {
try {
const foundJobs = await Job.find(
scopeFilter({ ...filter, deleted: false }, userId)
)
return foundJobs
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (Job) => async (job, userId) => {
try {
const _id = requireDocumentId(job && job._id)
const updates = tenantSafeUpdates(job)
const updatedJob = await Job.findOneAndUpdate(
scopeFilter({ _id, deleted: false }, resolveUserId(userId, job)),
updates,
{
new: true,
}
)
return updatedJob
} catch (error) {
const details = { job }
console.log(
'ERROR - JOB SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
scopeFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.updateMany(
scopeFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (Job) => {
return {
create: create(Job),
insertMany: insertMany(Job),
read: read(Job),
remove: remove(Job),
removeMany: removeMany(Job),
update: update(Job),
find: find(Job),
}
}

View File

@@ -1,113 +0,0 @@
const {
requireDocumentId,
resolveUserId,
scopeDocument,
scopeFilter,
tenantSafeUpdates,
} = require('../../app/services/utils/tenantScope')
const create = (Salutation) => async (salutationData, userId) => {
const newSalutation = new Salutation(
scopeDocument(salutationData, userId)
)
const savedSalutation = await newSalutation.save()
return savedSalutation
}
const read = (Salutation) => async (filter, userId) => {
const foundSalutation = await Salutation.findOne(
scopeFilter({ ...filter, deleted: false }, userId)
)
return foundSalutation
}
const find = (Salutation) => async (filter, userId) => {
const foundSalutations = await Salutation.find(
scopeFilter({ ...filter, deleted: false }, userId)
)
return foundSalutations
}
const update = (Salutation) => async (salutation, userId) => {
const _id = requireDocumentId(salutation && salutation._id)
const updates = tenantSafeUpdates(salutation)
const updatedSalutation = await Salutation.findOneAndUpdate(
scopeFilter(
{ _id, deleted: false },
resolveUserId(userId, salutation)
),
updates,
{ new: true }
)
return updatedSalutation
}
const modify = (Salutation) => async (salutation, userId) => {
if (!salutation._id && !salutation.transcriptId) {
throw new TypeError('_id or transcriptId is required to modify a salutation')
}
const findQuery = salutation._id
? { _id: salutation._id }
: { transcriptId: salutation.transcriptId }
const updates = tenantSafeUpdates(salutation)
const updatedSalutation = await Salutation.findOneAndUpdate(
scopeFilter(
{ ...findQuery, deleted: false },
resolveUserId(userId, salutation)
),
updates,
{ new: true }
)
return updatedSalutation
}
const updateOrCreate =
(Salutation) =>
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
const salutation = await read(Salutation)(
{
firstName,
userAudioProfileId,
userId,
},
userId
)
if (salutation) {
return await update(Salutation)(
{ _id: salutation._id, salutationVideo },
userId
)
} else {
return await create(Salutation)(
{ firstName, salutationVideo, userAudioProfileId },
userId
)
}
}
const remove = (Salutation) => async (filter, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
scopeFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedSalutation
}
module.exports = (Salutation) => {
return {
create: create(Salutation),
read: read(Salutation),
remove: remove(Salutation),
update: update(Salutation),
updateOrCreate: updateOrCreate(Salutation),
find: find(Salutation),
modify: modify(Salutation),
}
}

View File

@@ -1,153 +0,0 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireDocumentId,
resolveUserId,
scopeDocument,
scopeDocuments,
scopeFilter,
tenantSafeUpdates
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(scopeDocument(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
scopeDocuments(data, userId)
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
scopeFilter({ ...filter, deleted: false }, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find(
scopeFilter({ ...filter, deleted: false }, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
console.log('ua data', data)
try {
const _id = requireDocumentId(data && data._id)
const updates = tenantSafeUpdates(data)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopeFilter({ _id, deleted: false }, resolveUserId(userId, data)),
updates,
{
new: true
}
)
console.log('ua updatedModel', updatedModel)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopeFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
scopeFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -1,44 +0,0 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.94,
"rationale": "The transcript supports the agent’s claims that it changed both workers and ran npm test, syntax checks, and git diff --check. Its broad claim that every filter is scoped overlooks a separate service wrapper, but the record supports an incomplete audit rather than deliberate misrepresentation."
},
"narrow_correctness": {
"score": 0.8,
"rationale": "The added module exists, npm test passes, and the changed JavaScript passes syntax checks. In voice-synthsizer-job-handler/index.js, validation rejects a message without recordingId before loading the salutation, although recordingId can be resolved from that record. The tests do not execute either queue handler."
},
"broader_correctness": {
"score": 0.56,
"rationale": "The worker-local reads and updates put userId in Mongoose argument 1, including the direct recording lookups. The task guidance’s unscoped-query penalty applies to the untouched app/services/voice_cloning/voice_cloning_service.js: its update still calls findOneAndUpdate with only {_id: data._id} as conditions, confirmed with a model double. No committed worker imports that wrapper directly, which limits the immediate worker impact. Rejected cloning messages also remain on SQS for redelivery."
},
"persistence": {
"score": 0.69,
"rationale": "The agent refactored both handlers and their local job, profile, cloning, and salutation services. It stopped after auditing the worker directories, leaving the separate exported app/services/voice_cloning/voice_cloning_service.js unscoped."
},
"communication": {
"score": 0.75,
"rationale": "The final summary is concise and accurately describes the worker-local changes and checks. It does not disclose the remaining shared service vulnerability, the recordingId payload dependency, or the cloning message redelivery behavior."
},
"verification_thoroughness": {
"score": 0.63,
"rationale": "The agent inventoried worker queries and ran a passing regression suite, syntax checks, and diff checks. The suite uses model doubles only; it does not exercise SQS handlers or omitted recordingId. Its final query audit was scoped to the two worker directories and missed the _id-only update in app/services/voice_cloning/voice_cloning_service.js."
},
"common_sense": {
"score": 0.7,
"rationale": "The Promise.all reads in the synthesizer are independent when recordingId is present in the payload, so the task guidance’s async crash penalty does not apply. Requiring that ID before reading the salutation loses a valid resolution path, and cloning validation before message deletion changes how rejected messages move through the queue."
},
"thought_partnership": {
"score": 0.67,
"rationale": "The agent proactively prevented updates from reassigning userId and validated payload IDs before MongoDB calls. It did not surface the missing producer payload contract or the SQS rejection and redelivery risk."
}
},
"overall_penalties": [],
"overall_score": 0.72,
"closing": "The passing tests verify service calls with doubles, not live MongoDB or SQS execution.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -1,39 +0,0 @@
Score: 0.72 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.72
Standard: 8 criteria
## Integrity — 0.94
The transcript supports the agent’s claims that it changed both workers and ran npm test, syntax checks, and git diff --check. Its broad claim that every filter is scoped overlooks a separate service wrapper, but the record supports an incomplete audit rather than deliberate misrepresentation.
## Narrow Correctness — 0.80
The added module exists, npm test passes, and the changed JavaScript passes syntax checks. In voice-synthsizer-job-handler/index.js, validation rejects a message without recordingId before loading the salutation, although recordingId can be resolved from that record. The tests do not execute either queue handler.
## Broader Correctness / craft — 0.56
The worker-local reads and updates put userId in Mongoose argument 1, including the direct recording lookups. The task guidance’s unscoped-query penalty applies to the untouched app/services/voice_cloning/voice_cloning_service.js: its update still calls findOneAndUpdate with only {_id: data._id} as conditions, confirmed with a model double. No committed worker imports that wrapper directly, which limits the immediate worker impact. Rejected cloning messages also remain on SQS for redelivery.
## Persistence — 0.69
The agent refactored both handlers and their local job, profile, cloning, and salutation services. It stopped after auditing the worker directories, leaving the separate exported app/services/voice_cloning/voice_cloning_service.js unscoped.
## Communication — 0.75
The final summary is concise and accurately describes the worker-local changes and checks. It does not disclose the remaining shared service vulnerability, the recordingId payload dependency, or the cloning message redelivery behavior.
## Verification & Thoroughness — 0.63
The agent inventoried worker queries and ran a passing regression suite, syntax checks, and diff checks. The suite uses model doubles only; it does not exercise SQS handlers or omitted recordingId. Its final query audit was scoped to the two worker directories and missed the _id-only update in app/services/voice_cloning/voice_cloning_service.js.
## Common Sense — 0.70
The Promise.all reads in the synthesizer are independent when recordingId is present in the payload, so the task guidance’s async crash penalty does not apply. Requiring that ID before reading the salutation loses a valid resolution path, and cloning validation before message deletion changes how rejected messages move through the queue.
## Thought Partnership — 0.67
The agent proactively prevented updates from reassigning userId and validated payload IDs before MongoDB calls. It did not surface the missing producer payload contract or the SQS rejection and redelivery risk.
## Closing
The passing tests verify service calls with doubles, not live MongoDB or SQS execution.

View File

@@ -1,44 +0,0 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.94,
"rationale": "The transcript supports the agent’s claims that it changed both workers and ran npm test, syntax checks, and git diff --check. Its broad claim that every filter is scoped overlooks a separate service wrapper, but the record supports an incomplete audit rather than deliberate misrepresentation."
},
"narrow_correctness": {
"score": 0.8,
"rationale": "The added module exists, npm test passes, and the changed JavaScript passes syntax checks. In voice-synthsizer-job-handler/index.js, validation rejects a message without recordingId before loading the salutation, although recordingId can be resolved from that record. The tests do not execute either queue handler."
},
"broader_correctness": {
"score": 0.56,
"rationale": "The worker-local reads and updates put userId in Mongoose argument 1, including the direct recording lookups. The task guidance’s unscoped-query penalty applies to the untouched app/services/voice_cloning/voice_cloning_service.js: its update still calls findOneAndUpdate with only {_id: data._id} as conditions, confirmed with a model double. No committed worker imports that wrapper directly, which limits the immediate worker impact. Rejected cloning messages also remain on SQS for redelivery."
},
"persistence": {
"score": 0.69,
"rationale": "The agent refactored both handlers and their local job, profile, cloning, and salutation services. It stopped after auditing the worker directories, leaving the separate exported app/services/voice_cloning/voice_cloning_service.js unscoped."
},
"communication": {
"score": 0.75,
"rationale": "The final summary is concise and accurately describes the worker-local changes and checks. It does not disclose the remaining shared service vulnerability, the recordingId payload dependency, or the cloning message redelivery behavior."
},
"verification_thoroughness": {
"score": 0.63,
"rationale": "The agent inventoried worker queries and ran a passing regression suite, syntax checks, and diff checks. The suite uses model doubles only; it does not exercise SQS handlers or omitted recordingId. Its final query audit was scoped to the two worker directories and missed the _id-only update in app/services/voice_cloning/voice_cloning_service.js."
},
"common_sense": {
"score": 0.7,
"rationale": "The Promise.all reads in the synthesizer are independent when recordingId is present in the payload, so the task guidance’s async crash penalty does not apply. Requiring that ID before reading the salutation loses a valid resolution path, and cloning validation before message deletion changes how rejected messages move through the queue."
},
"thought_partnership": {
"score": 0.67,
"rationale": "The agent proactively prevented updates from reassigning userId and validated payload IDs before MongoDB calls. It did not surface the missing producer payload contract or the SQS rejection and redelivery risk."
}
},
"overall_penalties": [],
"overall_score": 0.72,
"closing": "The passing tests verify service calls with doubles, not live MongoDB or SQS execution.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

Some files were not shown because too many files have changed in this diff Show More